Example yes no or maybe

The program shown in Listing 22-4 provides three options, and lets the user choose one either by clicking it or by pressing a key.

Listing 22-4: Deathray.py import curses import curses.textpad import whrandom class CursesButton:

def _i nit_(self,Window,Y,X,Label,Hotkey=0):

self.Y=Y self.X=X self.Label=Label self.Width=len(Label)+2 # label, plus lines on side self.Underline=Underline

# Draw the button:

curses.textpad.rectangle(Window,Y,X,Y+2,X+self.Width)

# Draw the button label: Window.addstr(Y+1,X+1,Label,curses.A_BOLD)

# Make the hotkey stand out:

Window.addstr(Y+1,X+Underline+1,Label[Underline]

,curses.A_REVERSE) Window.refresh() def KeyPressed(self,Char):

if (Char>255): return 0 # skip control-characters if chr(Char).upper()==self.Label[self.Underline]:

return 1 else:

return 0

def MouseClicked(self,MouseEvent): (id,x,y,z,event)=MouseEvent if (self.Y <= y <= self.Y+2) and \ (self.X <= x < self.X+self.Width): return 1 else:

return 0

def ShowDialog(Window):

curses.mousemask(curses.BUTTON1_PRESSED)

Window.addstr(5,0,"Really, REALLY fire death ray?")

YesButton=CursesButton(Window,8,10,"Yes")

NoButton=CursesButton(Window,8,20,"No")

MaybeButton=CursesButton(Window,8,30,"Maybe")

Buttons=[YesButton,NoButton,MaybeButton]

Window.nodelay(l)

Action="" while 1:

Key=Window.getch() if (Key==-1): continue for Button in Buttons:

if Button.KeyPressed(Key): Action=Button.Label

# Handle mouse-events:

if (Key==curses.KEY_MOUSE):

MouseEvent=curses.getmouse() for Button in Buttons:

if Button.MouseClicked(MouseEvent): Action=Button.Label if Action!="": break # Handle the actions if (Action=="Yes"):

FireDeathRay(Window) if (Action=="No"): pass if (Action=="Maybe" and whrandom.random() > 0.5): FireDeathRay(Window)

def FireDeathRay(Window): Window.clear()

# Kra-ppoowwww! Frrrraapppp!!

Window.bkgd("X")

Window.nodelay(O)

Window.getch()

curses.wrapper(ShowDialog)

0 0

Post a comment