Skip to content

Commit

Permalink
Fixed button_box and integration into master
Browse files Browse the repository at this point in the history
Improved button_box to support multiple images in an array.  Still not
complete, but will be left undocumented for a while.
  • Loading branch information
robertlugg committed Jan 1, 2016
1 parent 8b7130e commit b7e55ee
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 23 deletions.
59 changes: 46 additions & 13 deletions easygui/boxes/button_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,15 @@ def demo_buttonbox_2():

# REF: http://stackoverflow.com/questions/1835018/python-check-if-an-object-is-a-list-or-tuple-but-not-string
def is_sequence(arg):
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__"))
return hasattr(arg, "__getitem__") or hasattr(arg, "__iter__")

def is_string(arg):
ret_val = None
try:
ret_val = isinstance(arg, basestring) #Python 2
except:
ret_val = isinstance(arg, str) #Python 3
return ret_val

def buttonbox(msg="",
title=" ",
Expand Down Expand Up @@ -156,6 +162,7 @@ def callback_ui(self, ui, command):
"""
if command == 'update': # Any button was pressed
self._text = ui.choice
self._choice_rc = ui.choice_rc
if self.callback:
# If a callback was set, call main process
self.callback(self)
Expand Down Expand Up @@ -184,6 +191,16 @@ def msg(self):
self._msg = ""
self.ui.set_msg(self._msg)

@property
def choice(self):
""" Name of button selected """
return self._text

@property
def choice_rc(self):
""" The row/column of the selected button (as a tuple) """
return self._choice_rc

# Methods to validate what will be sent to ui ---------

def to_string(self, something):
Expand Down Expand Up @@ -240,6 +257,7 @@ def __init__(self, msg, title, choices, images, default_choice, cancel_choice, c
self._cancel_choice = cancel_choice
self.callback = callback
self._choice_text = None
self._choice_rc = None
self._images = list()

self.boxRoot = tk.Tk()
Expand Down Expand Up @@ -269,6 +287,10 @@ def __init__(self, msg, title, choices, images, default_choice, cancel_choice, c
def choice(self):
return self._choice_text

@property
def choice_rc(self):
return self._choice_rc

# Run and stop methods ---------------------------------------

def run(self):
Expand Down Expand Up @@ -320,8 +342,9 @@ def cancel_pressed(self, event):
self._choice_text = self._cancel_choice
self.callback(self, command='cancel')

def button_pressed(self, button_text):
def button_pressed(self, button_text, button_rc):
self._choice_text = button_text
self._choice_rc = button_rc
self.callback(self, command='update')

def hotkey_pressed(self, event=None):
Expand Down Expand Up @@ -409,10 +432,16 @@ def create_images(self, filenames):
"""
if filenames is None:
return
if not is_sequence(filenames):
filenames = [filenames, ]
if is_sequence(filenames) and len(filenames) and not is_sequence(filenames[0]):
filenames = [filenames, ]
# Convert to a list of lists of filenames regardless of input
if is_string(filenames):
filenames = [[filenames,],]
elif is_sequence(filenames) and is_string(filenames[0]):
filenames = [filenames,]
elif is_sequence(filenames) and is_sequence(filenames[0]) and is_string(filenames[0][0]):
pass
else:
raise ValueError("Incorrect images argument.")

images = list()
for _r, images_row in enumerate(filenames):
row_number = len(filenames) - _r
Expand All @@ -421,13 +450,16 @@ def create_images(self, filenames):
try:
this_image['tk_image'] = ut.load_tk_image(filename)
except Exception as e:
raise
print(e)
this_image['tk_image'] = None
this_image['widget'] = tk.Button(
self.imagesFrame,
takefocus=1,
compound=tk.TOP)
this_image['widget'].configure(image=this_image['tk_image'])
this_image['widget'].configure(command=lambda text=filename: self.button_pressed(text)) ###NEXT: return instead the grid position????
if this_image['widget'] is not None:
this_image['widget'].configure(image=this_image['tk_image'])
fn = lambda text=filename, row=_r, column=column_number: self.button_pressed(text, (row, column))
this_image['widget'].configure(command=fn)
sticky_dir = tk.N+tk.S+tk.E+tk.W
this_image['widget'].grid(row=row_number, column=column_number, sticky=sticky_dir, padx='1m', pady='1m', ipadx='2m', ipady='1m')
self.imagesFrame.rowconfigure(row_number, weight=10, minsize='10m')
Expand All @@ -444,7 +476,7 @@ def create_buttons(self, choices, default_choice):
# Create buttons dictionary and Tkinter widgets
buttons = dict()
i_hack = 0
for button_text, unique_button_text in zip(choices, unique_choices):
for row, (button_text, unique_button_text) in enumerate(zip(choices, unique_choices)):
this_button = dict()
this_button['original_text'] = button_text
this_button['clean_text'], this_button['hotkey'], hotkey_position = ut.parse_hotkey(button_text)
Expand All @@ -453,7 +485,8 @@ def create_buttons(self, choices, default_choice):
takefocus=1,
text=this_button['clean_text'],
underline=hotkey_position)
this_button['widget'].configure(command=lambda text=button_text: self.button_pressed(text))
fn = lambda text=button_text, row=row, column=0: self.button_pressed(text, (row, column))
this_button['widget'].configure(command=fn)
this_button['widget'].grid(row=0, column=i_hack, padx='1m', pady='1m', ipadx='2m', ipady='1m')
self.buttonsFrame.columnconfigure(i_hack, weight=10)
i_hack += 1
Expand Down
2 changes: 1 addition & 1 deletion easygui/boxes/choice_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def get_pos(self):
global_state.window_position = '+' + geom.split('+', 1)[1]

def preselect_choice(self, preselect):
if preselect <> None:
if preselect != None:
self.choiceboxWidget.select_set(preselect)
self.choiceboxWidget.activate(preselect)

Expand Down
12 changes: 7 additions & 5 deletions test_cases/The Pirates of the Caribean Game.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
tries = 0

name = easygui.enterbox("Arrg its me Davy Jones whats your name ye scallywab")

easygui.msgbox("Do you fear DEATH "+name+" ? Lets play a game if ye win ye can go if ye lose then you are my a sailer on my ship the flying dutchman forever AHAAAA!")
txt = "Do you fear DEATH {}? Lets play a game if ye win ye can go if ye lose"
txt += " then you are my a sailer on my ship the flying dutchman forever AHAAAA!"
easygui.msgbox(txt.format(name))
easygui.msgbox("The game be simple ye get 15 chances to guess a number between 1 and 100. Ye be ready?")

while guess != secret and tries < 15:
guess = easygui.integerbox("What's your guess "+name)
if not guess: break
Expand All @@ -25,10 +27,10 @@
elif guess > secret:
easygui.msgbox(str(guess) + " is too high "+name)

tries = tries + 1
tries += 1

if guess == secret:
easygui.msgbox("Arrg ye got it in " +str(tries)+" you can go.")
easygui.msgbox("Arrg ye got it in {}. You can go.".format(tries))
if tries == 15:
easygui.msgbox("NO more guesses for ye your mine forever now "+name+"!! AHAAHAA!!!")
easygui.msgbox("NO more guesses for ye. You're mine forever now {} !! AHAAHAA!!!".format(name))

4 changes: 2 additions & 2 deletions test_cases/hex_entry.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

from __future__ import print_function
"""
Dec 23, 2014
Expand Down Expand Up @@ -86,4 +86,4 @@
if all([status == 'OK.' for status in fieldStatuses]):
break # no problems found, all statuses are 'OK'

print "Reply was:", fieldValues
print("Reply was:{}".format(fieldValues))
8 changes: 6 additions & 2 deletions test_cases/multiple_disney_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import easygui as eg

# A welcome message
eg.msgbox("Welcome to the quiz", "Quiz!")
reply = eg.msgbox("Welcome to the quiz", "Quiz!")
if reply is None:
exit()

while 1:
# Question 1
Expand All @@ -25,11 +27,13 @@
image = "mickey.gif"
choices = ["Mickey", "Minnie", "Daffy Duck", "Dave"]
reply = eg.buttonbox("Click on mickey:", images=images, choices=['Cancel'])
if reply=='Cancel':
print(reply)
if reply is None or reply=='Cancel':
break

if reply == images[0]:
eg.msgbox("Well done!", "Correct")
break
else:
eg.msgbox("Wrong", "Failure")

0 comments on commit b7e55ee

Please sign in to comment.