phython

profileterry1413
breezypythongui-programms.zip

breezypythongui.py

""" File: breezypythongui.py Version: 1.0 Copyright 2012 by Ken Lambert Resources for easy Python GUIs. LICENSE: This is open-source software released under the terms of the GPL (http://www.gnu.org/licenses/gpl.html). Its capabilities mirror those of BreezyGUI and BreezySwing, open-source frameworks for writing GUIs in Java, written by Ken Lambert and Martin Osborne. PLATFORMS: The package is a wrapper around tkinter (Python 3.X) and should run on any platform where tkinter is available. INSTALLATION: Put this file where Python can see it. """ import tkinter import tkinter.simpledialog N = tkinter.N S = tkinter.S E = tkinter.E W = tkinter.W CENTER = tkinter.CENTER END = tkinter.END NORMAL = tkinter.NORMAL DISABLED = tkinter.DISABLED NONE = tkinter.NONE WORD = tkinter.WORD VERTICAL = tkinter.VERTICAL HORIZONTAL = tkinter.HORIZONTAL RAISED = tkinter.RAISED SINGLE = tkinter.SINGLE ACTIVE = tkinter.ACTIVE class EasyFrame(tkinter.Frame): """Represents an application window.""" def __init__(self, title = "", width = None, height = None, background = "white", resizable = True): """Will shrink wrap the window around the widgets if width and height are not provided.""" tkinter.Frame.__init__(self, borderwidth = 4, relief = "sunken") if width and height: self.setSize(width, height) self.master.title(title) self.grid() # Expand the frame within the window self.master.rowconfigure(0, weight = 1) self.master.columnconfigure(0, weight = 1) self.grid(sticky = N+S+E+W) # Set the background color and resizability self.setBackground(background) self.setResizable(resizable) def setBackground(self, color): """Resets the window's background color to color.""" self["background"] = color def setResizable(self, state): """Resets the window's resizable property to True or False.""" self.master.resizable(state, state) def setSize(self, width, height): """Resets the window's width and height in pixels.""" self.master.geometry(str(width)+ "x" + str(height)) def setTitle(self, title): """Resets the window's title to title.""" self.master.title(title) # Methods to add widgets to the window. The row and column in # the grid are required arguments. def addLabel(self, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None, background = "white", foreground = "black"): """Creates and inserts a label at the row and column, and returns the label.""" label = tkinter.Label(self, text = text, font = font, background = background, foreground = foreground) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addButton(self, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): """Creates and inserts a button at the row and column, and returns the button.""" button = tkinter.Button(self, text = text, command = command, state = state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addFloatField(self, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): """Creates and inserts a float field at the row and column, and returns the float field.""" field = FloatField(self, value, width, precision, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): """Creates and inserts an integer field at the row and column, and returns the integer field.""" field = IntegerField(self, value, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): """Creates and inserts a text field at the row and column, and returns the text field.""" field = TextField(self, text, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextArea(self, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): """Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.""" frame = tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) xScroll = tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll["command"] = area.xview yScroll["command"] = area.yview return area def addListbox(self, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): """Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.""" frame = tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll["command"] = listBox.yview return listBox def addCanvas(self, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = "white"): """Creates and inserts a canvas at the row and column, and returns the canvas.""" if not canvas: canvas = EasyCanvas(self, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) self.columnconfigure(column, weight = 10) self.rowconfigure(row, weight = 10) return canvas def addScale(self, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = "", length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): """Creates and inserts a scale at the row and column, and returns the scale.""" scale = tkinter.Scale(self, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = "sunken", borderwidth = 4) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addMenuBar(self, row, column, rowspan = 1, columnspan = 1, orient = "horizontal"): """Creates and inserts a menu bar at the row and column, and returns the menu bar.""" if not orient in ("horizontal", "vertical"): raise ValueError("orient must be horizontal or vertical") menuBar = EasyMenuBar(self, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def addCheckbutton(self, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): """Creates and inserts check button at the row and column, and returns the check button.""" cb = EasyCheckbutton(self, text, command) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): """Creates and returns a radio button group.""" return EasyRadiobuttonGroup(self, row, column, rowspan, columnspan, orient) # Added 12-18-2012 def addPanel(self, row, column, rowspan = 1, columnspan = 1, background = "white"): """Creates and returns a panel.""" return EasyPanel(self, row, column, rowspan, columnspan, background) # Method to pop up a message box from this window. def messageBox(self, title = "", message = "", width = 25, height = 5): """Creates and pops up a message box, with the given title, message, and width and height in rows and columns of text.""" dlg = MessageBox(self, title, message, width, height) return dlg.modified() # Method to pop up a prompter box from this window. def prompterBox(self, title = "", promptString = "", inputText = "", fieldWidth = 20): """Creates and pops up a prompter box, with the given title, prompt, input text, and field width in columns of text. Returns the text entered at the prompt.""" dlg = PrompterBox(self, title, promptString, inputText, fieldWidth) return dlg.getText() # Classes for easy widgets class AbstractField(tkinter.Entry): """Represents common features of float fields, integer fields, and text fields.""" def __init__(self, parent, value, width, state): self.var = tkinter.StringVar() self.setValue(value) tkinter.Entry.__init__(self, parent, textvariable = self.var, width = width, state = state) def setValue(self, value): self.var.set(value) def getValue(self): return self.var.get() class FloatField(AbstractField): """Represents a single line box for I/O of floats.""" def __init__(self, parent, value, width, precision, state): self.setPrecision(precision) AbstractField.__init__(self, parent, value, width, state) def getNumber(self): """Returns the float contained in the field. Raises: ValueError if number format is bad.""" return float(self.getValue()) def setNumber(self, number): """Replaces the float contained in the field.""" self.setValue(self._precision % number) def setPrecision(self, precision): """Resets the precision for the display of a float.""" if precision and precision >= 0: self._precision = "%0." + str(precision) + "f" else: self._precision = "%f" class IntegerField(AbstractField): """Represents a single line box for I/O of integers.""" def __init__(self, parent, value, width, state): AbstractField.__init__(self, parent, value, width, state) def getNumber(self): """Returns the integer contained in the field. Raises: ValueError if number format is bad.""" return int(self.getValue()) def setNumber(self, number): """Replaces the integer contained in the field.""" self.setValue(str(number)) class TextField(AbstractField): """Represents a single line box for I/O of strings.""" def __init__(self, parent, value, width, state): AbstractField.__init__(self, parent, value, width, state) def getText(self): """Returns the string contained in the field.""" return self.getValue() def setText(self, text): """Replaces the string contained in the field.""" self.setValue(text) class TextArea(tkinter.Text): """Represents a box for I/O of multiline text.""" def __init__(self, parent, text, width, height, xscrollcommand, yscrollcommand, wrap): tkinter.Text.__init__(self, parent, width = width, height = height, wrap = wrap, xscrollcommand = xscrollcommand, yscrollcommand = yscrollcommand) self.setText(text) def getText(self): """Returns the string contained in the text area.""" return self.get("1.0", END) def setText(self, text): """Replaces the string contained in the text area.""" self.delete("1.0", END) self.insert("1.0", text) def appendText(self, text): """Inserts the text after the string contained in the text area.""" self.insert(END, text) class EasyListbox(tkinter.Listbox): """Represents a list box.""" def __init__(self, parent, width, height, yscrollcommand, listItemSelected): self._listItemSelected = listItemSelected tkinter.Listbox.__init__(self, parent, width = width, height = height, yscrollcommand = yscrollcommand, selectmode = SINGLE) self.bind("<<ListboxSelect>>", self.triggerListItemSelected) def triggerListItemSelected(self, event): """Strategy method to respond to an item selection in the list box. Runs the client's listItemSelected method with the selected index if there is one.""" if self.size() == 0: return widget = event.widget index = widget.curselection()[0] self._listItemSelected(index) def getSelectedIndex(self): """Returns the index of the selected item or -1 if no item is selected.""" tup = self.curselection() if len(tup) == 0: return -1 else: return int(tup[0]) def getSelectedItem(self): """Returns the selected item or the empty string if no item is selected.""" index = self.getSelectedIndex() if index == -1: return "" else: return self.get(index) def setSelectedIndex(self, index): """Selects the item at the index if it's in the range.""" if index < 0 or index >= self.size(): return self.selection_set(index, index) def clear(self): """Deletes all items from the list box.""" while self.size() > 0: self.delete(0) def getIndex(self, item): """Returns the index of item if it's in the list box, or -1 otherwise.""" tup = self.get(0, self.size() - 1) if item in tup: return tup.index(item) else: return -1 class EasyRadiobuttonGroup(tkinter.Frame): """Represents a group of radio buttons, only one of which is selected at any given time.""" def __init__(self, parent, row, column, rowspan, columnspan, orient): tkinter.Frame.__init__(self, parent) self.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+S+E+W) self._commonVar = tkinter.StringVar("") self._buttons = dict() self._orient = orient self._buttonRow = self._buttonColumn = 0 def addRadiobutton(self, text, command = lambda : 0): """Creates a button with the given text and command, adds it to the group, and returns the button.""" if text in self._buttons: raise ValueError("Button with this label already in the group") button = tkinter.Radiobutton(self, text = text, value = text, command = command, variable = self._commonVar) self._buttons[text] = button button.grid(row = self._buttonRow, column = self._buttonColumn, sticky = N+W) if self._orient == VERTICAL: self.rowconfigure(self._buttonRow, weight = 1) self._buttonRow += 1 else: self.columnconfigure(self._buttonColumn, weight = 1) self._buttonColumn += 1 return button def getSelectedButton(self): if not self._commonVar.get() in self._buttons: raise ValueError("No button has been selected yet.") return self._buttons[self._commonVar.get()] def setSelectedButton(self, button): self._commonVar.set(button["value"]) class EasyCheckbutton(tkinter.Checkbutton): """Represents a check button.""" def __init__(self, parent, text, command): self._variable = tkinter.IntVar() tkinter.Checkbutton.__init__(self, parent, text = text, variable = self._variable, command = command) def isChecked(self): """Returns True if the button is checked or False otherwise.""" return self._variable.get() != 0 class EasyMenuBar(tkinter.Frame): """Represents a menu bar.""" def __init__(self, parent, orient): self._orient = orient self._row = self._column = 0 tkinter.Frame.__init__(self, parent, relief = RAISED, borderwidth = 1) def addMenu(self, text, state = NORMAL): """Creates and inserts a menu into the menubar, and returns the menu.""" menu = EasyMenubutton(self, text, state = state) menu.grid(row = self._row, column = self._column) if self._orient == "horizontal": self._column += 1 else: self._row += 1 return menu class EasyMenubutton(tkinter.Menubutton): """Represents a menu button.""" def __init__(self, menuBar, text, state): tkinter.Menubutton.__init__(self, menuBar, text = text, state = state) self.menu = tkinter.Menu(self) self["menu"] = self.menu self._currentIndex = -1 def addMenuItem(self, text, command, state = NORMAL): """Inserts a menu option in the given menu.""" self.menu.add_command(label = text, command = command, state = state) self._currentIndex += 1 return EasyMenuItem(self, self._currentIndex) class EasyMenuItem(object): """Represents an option in a drop-down menu.""" def __init__(self, menu, index): self._menu = menu self._index = index def setState(self, state): """Sets the state of the item to state.""" self._menu.menu.entryconfigure(self._index, state = state) class EasyCanvas(tkinter.Canvas): """Represents a rectangular area for interactive drawing of shapes. Supports simple commands for drawing lines, rectangles, and ovals, as well as methods for responding to mouse events in the canvas.""" def __init__(self, parent, width = None, height = None, background = "white"): tkinter.Canvas.__init__(self, parent, width = width, height = height, background = background) self.bind("<Double-Button-1>", self.mouseDoubleClicked) self.bind("<ButtonPress-1>", self.mousePressed) self.bind("<ButtonRelease-1>", self.mouseReleased) self.bind("<B1-Motion>", self.mouseDragged) # Mouse event handling methods. One or more of these methods can # be overridden in the subclass to implement the required actions. # The event argument can be used to extract the current mouse # cursor coordinates (event.x and event.y). def mouseDoubleClicked(self, event): """Triggered when the mouse is double-clicked in the area of this canvas.""" return def mousePressed(self, event): """Triggered when the mouse is pressed in the area of this canvas.""" return def mouseReleased(self, event): """Triggered when the mouse is released in the area of this canvas.""" return def mouseDragged(self, event): """Triggered when the mouse is dragged in the area of this canvas.""" return def getWidth(self): """Returns the width of the canvas.""" return self["width"] def getHeight(self): """Returns the height of the canvas.""" return self["height"] def drawLine(self, x0, y0, x1, y1, fill = "black", width = 1): item = self.create_line(x0, y0, x1, y1) self.itemconfig(item, fill = fill, width = width) return item def drawRectangle(self, x0, y0, x1, y1, outline = "black", fill = None): """Draws a rectangle with the given corner points, outline color, and fill color.""" item = self.create_rectangle(x0, y0, x1, y1) self.itemconfig(item, outline = outline, fill = fill) return item def drawOval(self, x0, y0, x1, y1, outline = "black", fill = None): """Draws an ovel within the given corner points, with the given outline color and fill color.""" item = self.create_oval(x0, y0, x1, y1) self.itemconfig(item, outline = outline, fill = fill) return item def drawText(self, text, x, y, fill = "black"): """Draws the given text (a string) at the given coordinates with the given fill color. The string is centered vertically and horizontally at the given coordinates.""" item = self.create_text(x, y) self.itemconfig(item, text = text, fill = fill) return item def drawImage(self, image, x, y, anchor = CENTER): """Draws the given image (a PhotoImage) at the given coordinates. The image is centered at the given coordinates by default.""" item = self.create_image(x, y, image = image, anchor = anchor) self.itemconfig(item, image = image, anchor = anchor) return item def deleteItem(self, item): """Removes and erases the shape with the given item number from the canvas.""" self.delete(item) # Support classes for dialogs. class MessageBox(tkinter.simpledialog.Dialog): """Represents a message dialog with a scrollable text area.""" @classmethod def message(cls, title = "", message = "", width = 25, height = 5): MessageBox(tkinter.Frame(), title, message, width, height) def __init__(self, parent, title, message, width, height): """Set up the window and widgets.""" self._message = message self._width = width self._height = height self._modified = False tkinter.simpledialog.Dialog.__init__(self, parent, title) def body(self, master): self.resizable(0, 0) yScroll = tkinter.Scrollbar(master, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) output = tkinter.Text(master, width = self._width, height = self._height, padx = 5, pady = 5, wrap = WORD, yscrollcommand = yScroll.set) output.grid(row = 0, column = 0, sticky = N+W+S+E) output.insert("1.0", self._message) output["state"] = DISABLED yScroll["command"] = output.yview return output def buttonbox(self): '''add standard button box. override if you do not want the standard buttons''' box = tkinter.Frame(self) w = tkinter.Button(box, text="OK", width = 10, command = self.ok, default = ACTIVE) w.pack() self.bind("<Return>", self.ok) box.pack() def apply(self): """Quits the dialog.""" self._modified = True def modified(self): return self._modified class PrompterBox(tkinter.simpledialog.Dialog): """Represents an input dialog with a text field.""" @classmethod def prompt(cls, title = "", promptString = "", inputText = "", fieldWidth = 20): """Creates and pops up an input dialog.""" dlg = PrompterBox(tkinter.Frame(), title, promptString, inputText, fieldWidth) return dlg.getText() def __init__(self, parent, title, promptString, inputText, fieldWidth): """Set up the window and widgets.""" self._prompt = promptString self._text = inputText self._width = fieldWidth self._modified = False tkinter.simpledialog.Dialog.__init__(self, parent, title) def body(self, master): self.resizable(0, 0) label = tkinter.Label(master, text = self._prompt) label.grid(row = 0, column = 0, padx = 5, sticky = N+W+S+E) self._field = TextField(master, self._text, self._width, NORMAL) self._field.grid(row = 1, column = 0, padx = 5, sticky = N+W+S+E) return self._field def buttonbox(self): '''add standard button box. override if you do not want the standard buttons''' box = tkinter.Frame(self) w = tkinter.Button(box, text="OK", width = 10, command = self.ok, default = ACTIVE) w.pack() self.bind("<Return>", self.ok) box.pack() def apply(self): """Quits the dialog.""" self._modified = True def modified(self): return self._modified def getText(self): """Returns the text currently in the text field.""" return self._field.getText() class EasyDialog(tkinter.simpledialog.Dialog): """Represents a general-purpose dialog. Subclasses should include body and apply methods.""" def __init__(self, parent, title = ""): """Set up the window and widgets.""" self._modified = False tkinter.simpledialog.Dialog.__init__(self, parent, title) def modified(self): """Returns the modified status of the dialog.""" return self._modified def setModified(self): self._modified = True def addLabel(self, master, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None): """Creates and inserts a label at the row and column, and returns the label.""" label = tkinter.Label(master, text = text, font = font) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addButton(self, master, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): """Creates and inserts a button at the row and column, and returns the button.""" button = tkinter.Button(master, text = text, command = command, state = state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addFloatField(self, master, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): """Creates and inserts a float field at the row and column, and returns the float field.""" field = FloatField(master, value, width, precision, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, master, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): """Creates and inserts an integer field at the row and column, and returns the integer field.""" field = IntegerField(master, value, width, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, master, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): """Creates and inserts a text field at the row and column, and returns the text field.""" field = TextField(master, text, width, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addCheckbutton(self, master, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): """Creates and inserts check button at the row and column, and returns the check button.""" cb = EasyCheckbutton(master, text, command) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, master, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): """Creates and returns a radio button group.""" return EasyRadiobuttonGroup(master, row, column, rowspan, columnspan, orient) def addScale(self, master, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = "", length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): """Creates and inserts a scale at the row and column, and returns the scale.""" scale = tkinter.Scale(master, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = "sunken", borderwidth = 4) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addTextArea(self, master, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): """Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.""" frame = tkinter.Frame(master) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) master.columnconfigure(column, weight = 1) master.rowconfigure(row, weight = 1) xScroll = tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll["command"] = area.xview yScroll["command"] = area.yview return area def addListbox(self, master, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): """Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.""" frame = tkinter.Frame(master) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) master.columnconfigure(column, weight = 1) master.rowconfigure(row, weight = 1) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll["command"] = listBox.yview return listBox def addCanvas(self, master, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = "white"): """Creates and inserts a canvas at the row and column, and returns the canvas.""" if not canvas: canvas = EasyCanvas(master, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) master.columnconfigure(column, weight = 10) master.rowconfigure(row, weight = 10) return canvas def addMenuBar(self, master, row, column, rowspan = 1, columnspan = 1, orient = "horizontal"): """Creates and inserts a menu bar at the row and column, and returns the menu bar.""" if not orient in ("horizontal", "vertical"): raise ValueError("orient must be horizontal or vertical") menuBar = EasyMenuBar(master, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def messageBox(self, title = "", message = "", width = 25, height = 5): """Creates and pops up a message box, with the given title, message, and width and height in rows and columns of text.""" dlg = MessageBox(self, title, message, width, height) return dlg.modified() # Added 12-18-2012 def addPanel(self, master, row, column, rowspan = 1, columnspan = 1, background = "white"): """Creates and returns a panel.""" return EasyPanel(master, row, column, rowspan, columnspan, background) # Added 12-18-2012 class EasyPanel(tkinter.Frame): """Organizes a group of widgets in a panel (nested frame).""" def __init__(self, parent, row, column, rowspan, columnspan, background): tkinter.Frame.__init__(self, parent) parent.rowconfigure(row, weight = 1) parent.columnconfigure(column, weight = 1) self.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+S+E+W) self.setBackground(background) def setBackground(self, color): """Resets the panel's background color to color.""" self["background"] = color def addButton(self, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): """Creates and inserts a button at the row and column, and returns the button.""" button = tkinter.Button(self, text = text, command = command, state = state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addLabel(self, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None, background = "white", foreground = "black"): """Creates and inserts a label at the row and column, and returns the label.""" label = tkinter.Label(self, text = text, font = font, background = background, foreground = foreground) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addFloatField(self, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): """Creates and inserts a float field at the row and column, and returns the float field.""" field = FloatField(self, value, width, precision, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): """Creates and inserts an integer field at the row and column, and returns the integer field.""" field = IntegerField(self, value, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): """Creates and inserts a text field at the row and column, and returns the text field.""" field = TextField(self, text, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextArea(self, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): """Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.""" frame = tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) xScroll = tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll["command"] = area.xview yScroll["command"] = area.yview return area def addListbox(self, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): """Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.""" frame = tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) yScroll = tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll["command"] = listBox.yview return listBox def addCanvas(self, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = "white"): """Creates and inserts a canvas at the row and column, and returns the canvas.""" if not canvas: canvas = EasyCanvas(self, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) self.columnconfigure(column, weight = 10) self.rowconfigure(row, weight = 10) return canvas def addScale(self, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = "", length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): """Creates and inserts a scale at the row and column, and returns the scale.""" scale = tkinter.Scale(self, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = "sunken", borderwidth = 4) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addMenuBar(self, row, column, rowspan = 1, columnspan = 1, orient = "horizontal"): """Creates and inserts a menu bar at the row and column, and returns the menu bar.""" if not orient in ("horizontal", "vertical"): raise ValueError("orient must be horizontal or vertical") menuBar = EasyMenuBar(self, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def addCheckbutton(self, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): """Creates and inserts check button at the row and column, and returns the check button.""" cb = EasyCheckbutton(self, text, command) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): """Creates and returns a radio button group.""" return EasyRadiobuttonGroup(self, row, column, rowspan, columnspan, orient) def addPanel(self, row, column, rowspan = 1, columnspan = 1, background = "white"): """Creates and returns a panel.""" return EasyPanel(self, row, column, rowspan, columnspan, background)

buttondemo.py

""" File: buttondemo.py """ from breezypythongui import EasyFrame class ButtonDemo(EasyFrame): """Illustrates command buttons and user events.""" def __init__(self): """Sets up the window, label, and buttons.""" EasyFrame.__init__(self, title = "Button Demo") # A single label in the first row. self.label = self.addLabel(text = "Hello world!", row = 0, column = 0, columnspan = 2, sticky = "NSEW") # Two command buttons in the second row. self.clearBtn = self.addButton(text = "Clear", row = 1, column = 0, command = self.clear) self.restoreBtn = self.addButton(text = "Restore", row = 1, column = 1, command = self.restore, state = "disabled") # Methods to handle user events. def clear(self): """Resets the label to the empty string and the button states.""" self.label["text"] = "" self.clearBtn["state"] = "disabled" self.restoreBtn["state"] = "normal" def restore(self): """Resets the label to 'Hello world!'and sets the state of the buttons.""" self.label["text"] = "Hello world!" self.clearBtn["state"] = "normal" self.restoreBtn["state"] = "disabled" def main(): """Instantiate and pop up the window.""" ButtonDemo().mainloop() if __name__ == "__main__": main()

checkbuttondemo.py

""" File: checkbuttondemo.py Author: Kenneth A. Lambert """ from breezypythongui import EasyFrame class CheckbuttonDemo(EasyFrame): """Allows the user to place a restaurant order from a set of options.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, "Check Button Demo") # Add four check buttons self.chickCB = self.addCheckbutton(text = "Chicken", row = 0, column = 0) self.taterCB = self.addCheckbutton(text = "French fries", row = 0, column = 1) self.beanCB = self.addCheckbutton(text = "Green beans", row = 1, column = 0) self.sauceCB = self.addCheckbutton(text = "Applesauce", row = 1, column = 1) self.addButton(text = "Place order", row = 2, column = 0, columnspan = 2, command = self.placeOrder) # Event handler method def placeOrder(self): """Display a message box with the order information.""" message = "" if self.chickCB.isChecked(): message += "Chicken\n\n" if self.taterCB.isChecked(): message += "French fries\n\n" if self.beanCB.isChecked(): message += "Green beans\n\n" if self.sauceCB.isChecked(): message += "Applesauce\n" if message == "": message = "No food ordered!" self.messageBox(title = "Customer Order", message = message) def main(): """Instantiate and pop up the window.""" CheckbuttonDemo().mainloop() if __name__ == "__main__": main()

colorchooserdemo.py

""" File: colorchooserdemo.py """ from breezypythongui import EasyFrame import tkinter.colorchooser class ColorchooserDemo(EasyFrame): """Displays the results of picking a color.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = "Color Chooser Demo") # Labels and output fields self.addLabel('R', row = 0, column = 0) self.addLabel('G', row = 1, column = 0) self.addLabel('B', row = 2, column = 0) self.addLabel("Color", row = 3, column = 0) self.r = self.addIntegerField(0, row = 0, column = 1) self.g = self.addIntegerField(0, row = 1, column = 1) self.b = self.addIntegerField(0, row = 2, column = 1) self.hex = self.addTextField(text = "#000000", row = 3, column = 1, width = 10) # Canvas with an initial black background self.canvas = self.addCanvas(row = 0, column = 2, rowspan = 4, width = 50, background = "#000000") # Command button self.addButton(text = "Choose color", row = 4, column = 0, columnspan = 3, command = self.chooseColor) # Event handling method def chooseColor(self): """Pops up a color chooser and outputs the results.""" colorTuple = tkinter.colorchooser.askcolor() if not colorTuple[0]: return ((r, g, b), hexString) = colorTuple self.r.setNumber(int(r)) self.g.setNumber(int(g)) self.b.setNumber(int(b)) self.hex.setText(hexString) self.canvas["background"] = hexString def main(): """Instantiate and pop up the window.""" ColorchooserDemo().mainloop() if __name__ == "__main__": main()

counterdemo.py

""" File: counterdemo.py """ from breezypythongui import EasyFrame class CounterDemo(EasyFrame): """Illustrates the use of a counter with an instance variable.""" def __init__(self): """Sets up the window, label, and buttons.""" EasyFrame.__init__(self, title = "Counter Demo") self.setSize(200, 75) # Instance variable to track the count. self.count = 0 # A label to displat the count in the first row. self.label = self.addLabel(text = "0", row = 0, column = 0, sticky = "NSEW", columnspan = 2) # Two command buttons. self.addButton(text = "Next", row = 1, column = 0, command = self.next) self.addButton(text = "Reset", row = 1, column = 1, command = self.reset) # Methods to handle user events. def next(self): """Increments the count and updates the display.""" self.count += 1 self.label["text"] = str(self.count) def reset(self): """Resets the count to 0 and updates the display.""" self.count = 0 self.label["text"] = str(self.count) def main(): """Entry point for the application.""" CounterDemo().mainloop() if __name__ == "__main__": main()

filedialogdemo.py

""" File: filedialogdemo.py """ from breezypythongui import EasyFrame import tkinter.filedialog class FileDialogDemo(EasyFrame): """Demonstrates the use of a file dialog.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, "File Dialog Demo") self.outputArea = self.addTextArea("", row = 0, column = 0, width = 80, height = 15) self.addButton(text = "Open", row = 1, column = 0, command = self.openFile) # Event handling method. def openFile(self): """Pops up an open file dialog, and if a file is selected, displays its text in the text area and its pathname in the title bar.""" fList = [("Python files", "*.py"), ("Text files", "*.txt")] fileName = tkinter.filedialog.askopenfilename(parent = self, filetypes = fList) if fileName != "": file = open(fileName, 'r') text = file.read() file.close() self.outputArea.setText(text) self.setTitle(fileName) def main(): """Instantiate and pop up the window.""" FileDialogDemo().mainloop() if __name__ == "__main__": main()

guessversion1.py

""" File: guessversion1.py Lays out the user interface for a GUI-based guessing game. """ import random from breezypythongui import EasyFrame class GuessingGame(EasyFrame): """Plays a guessing game with the user.""" def __init__(self): """Sets up the window,widgets, and data.""" EasyFrame.__init__(self, title = "Gussing Game") self.myNumber = random.randint(1, 100) self.count = 0 greeting = "Guess a number between 1 and 100." self.hintLabel = self.addLabel(text = greeting, row = 0, column = 0, sticky = "NSEW", columnspan = 2) self.addLabel(text = "Your guess", row = 1, column = 0) self.guessField = self.addIntegerField(0, row = 1, column = 1) self.nextButton = self.addButton(text = "Next", row = 2, column = 0) self.newButton = self.addButton(text = "New game", row = 2, column = 1) def main(): """Instantiate and pop up the window.""" GuessingGame().mainloop() if __name__ == "__main__": main()

guessversion2.py

""" File: guessversion1.py Lays out the user interface for a GUI-based guessing game and completes the game logic. """ 4 import random from breezypythongui import EasyFrame class GuessingGame(EasyFrame): """Plays a guessing game with the user.""" def __init__(self): """Sets up the window,widgets, and data.""" EasyFrame.__init__(self, title = "Guessing Game") self.myNumber = random.randint(1, 100) self.count = 0 greeting = "Guess a number between 1 and 100." self.hintLabel = self.addLabel(text = greeting, row = 0, column = 0, sticky = "NSEW", columnspan = 2) self.addLabel(text = "Your guess", row = 1, column = 0) self.guessField = self.addIntegerField(0, row = 1, column = 1) self.nextButton = self.addButton(text = "Next", row = 2, column = 0, command = self.nextGuess) self.newButton = self.addButton(text = "New game", row = 2, column = 1, command = self.newGame) def nextGuess(self): """Processes the user's next guess.""" self.count += 1 guess = self.guessField.getNumber() if guess == self.myNumber: self.hintLabel["text"] = "You've guessed it in " + \ str(self.count) + " attempts!" self.nextButton["state"] = "disabled" elif guess < self.myNumber: self.hintLabel["text"] = "Sorry, too small!" else: self.hintLabel["text"] = "Sorry, too large!" def newGame(self): """Resets the GUI to its original state.""" self.myNumber = random.randint(1, 100) self.count = 0 greeting = "Guess a number between 1 and 100." self.hintLabel["text"] = greeting self.guessField.setNumber(0) self.nextButton["state"] = "normal" def main(): """Instantiate and pop up the window.""" GuessingGame().mainloop() if __name__ == "__main__": main()

imagebuttondemo.py

""" File: imagebuttondemo.py """ from breezypythongui import EasyFrame from tkinter import PhotoImage from tkinter.font import Font class ImageButtonDemo(EasyFrame): """Displays an image button and a caption.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = "Image Button Demo") self.setResizable(False) # Add the labels to the window. imageButton = self.addButton(text = "", row = 0, column = 0, command = self.smokey) textLabel = self.addLabel(text = "Smokey the cat", row = 1, column = 0, sticky = "NSEW") # Load the image and associate it with the image label. self.image = PhotoImage(file = "smokey.gif") imageButton["image"] = self.image # Set the font and color of the caption. font = Font(family = "Verdana", size = 20, slant = "italic") textLabel["font"] = font textLabel["foreground"] = "blue" def smokey(self): self.messageBox(message = "Hi, I'm Smokey!") def main(): """Instantiates and pops up the window.""" ImageButtonDemo().mainloop() if __name__ == "__main__": main()

imagedemo.py

""" File: imagedemo.py """ from breezypythongui import EasyFrame from tkinter import PhotoImage from tkinter.font import Font class ImageDemo(EasyFrame): """Displays an image and a caption.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = "Image Demo") self.setResizable(False) # Add the labels to the window. imageLabel = self.addLabel(text = "", row = 0, column = 0, sticky = "NSEW") textLabel = self.addLabel(text = "Smokey the cat", row = 1, column = 0, sticky = "NSEW") # Load the image and associate it with the image label. self.image = PhotoImage(file = "smokey.gif") imageLabel["image"] = self.image # Set the font and color of the caption. font = Font(family = "Verdana", size = 20, slant = "italic") textLabel["font"] = font textLabel["foreground"] = "blue" def main(): """Instantiates and pops up the window.""" ImageDemo().mainloop() if __name__ == "__main__": main()

labeldemo.py

""" File: labeldemo.py """ from breezypythongui import EasyFrame class LabelDemo(EasyFrame): """Displays a greeting in a window.""" def __init__(self): """Sets up the window and the label.""" EasyFrame.__init__(self) self.addLabel(text = "Hello world!", row = 0, column = 0) def main(): """Instantiates and pops up the window.""" LabelDemo().mainloop() if __name__ == "__main__": main()

layoutdemo.py

""" File: layoutdemo.py """ from breezypythongui import EasyFrame class LayoutDemo(EasyFrame): """Displays labels in the quadrants.""" def __init__(self): """Sets up the window and the labels.""" EasyFrame.__init__(self) self.addLabel(text = "(0, 0)", row = 0, column = 0) self.addLabel(text = "(0, 1)", row = 0, column = 1) self.addLabel(text = "(1, 0)", row = 1, column = 0) self.addLabel(text = "(1, 1)", row = 1, column = 1) def main(): """Instantiate and pop up the window.""" LayoutDemo().mainloop() if __name__ == "__main__": main()

numberfielddemo.py

""" File: numberfielddemo.py """ from breezypythongui import EasyFrame import math class NumberFieldDemo(EasyFrame): """Computes and displays the square root of an input number.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = """Number Field Demo""") # Label and field for the input self.addLabel(text = "An integer", row = 0, column = 0) self.inputField = self.addIntegerField(value = 0, row = 0, column = 1, width = 10) # Label and field for the output self.addLabel(text = "Square root", row = 1, column = 0) self.outputField = self.addFloatField(value = 0.0, row = 1, column = 1, width = 8, precision = 2, state = "readonly") # The command button self.addButton(text = "Compute", row = 2, column = 0, columnspan = 2, command = self.computeSqrt) # The event handling method for the button def computeSqrt(self): """Inputs the integer, computes the square root, and outputs the result.""" number = self.inputField.getNumber() result = math.sqrt(number) self.outputField.setNumber(result) def main(): """Instantiate and pop up the window.""" NumberFieldDemo().mainloop() if __name__ == "__main__": main()

numberfielddemowithmessage.py

""" File: numberfielddemowithmessage.py Adds error handling with a message box. """ from breezypythongui import EasyFrame import math class NumberFieldDemo(EasyFrame): """Computes and displays the square root of an input number.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = """Number Field Demo""") # Label and field for the input self.addLabel(text = "An integer", row = 0, column = 0) self.inputField = self.addIntegerField(value = 0, row = 0, column = 1, width = 10) # Label and field for the output self.addLabel(text = "Square root", row = 1, column = 0) self.outputField = self.addFloatField(value = 0.0, row = 1, column = 1, width = 8, precision = 2, state = "readonly") # The command button self.addButton(text = "Compute", row = 2, column = 0, columnspan = 2, command = self.computeSqrt) # The event handling method for the button def computeSqrt(self): """Inputs the integer, computes the square root, and outputs the result.""" try: number = self.inputField.getNumber() result = math.sqrt(number) self.outputField.setNumber(result) except ValueError: self.messageBox(title = "ERROR", message = "Input must be an integer >= 0") def main(): """Instantiate and pop up the window.""" NumberFieldDemo().mainloop() if __name__ == "__main__": main()

paneldemoversion1.py

""" File: paneldemoversion1.py A complex layout without nested frames. """ from breezypythongui import EasyFrame class PanelDemo(EasyFrame): def __init__(self): # Create the main frame EasyFrame.__init__(self, "Panel Demo - v1") # Create and add widgets to the window self.addLabel(text = "Label 1", row = 0, column = 0) self.addTextField(text = "Text1", row = 0, column = 1, columnspan = 2) self.addLabel(text = "Label 2", row = 1, column = 0) self.addTextField(text = "Text2", row = 1, column = 1, columnspan = 2) # Create and add buttons to the window self.addButton(text = "B1", row = 2, column = 0) self.addButton(text = "B2", row = 2, column = 1) self.addButton(text = "B3", row = 2, column = 2) def main(): """Instantiate and pop up the window.""" PanelDemo().mainloop() if __name__ == "__main__": main()

paneldemoversion2.py

""" File: paneldemoversion2.py A complex layout with two panels representing nested frames. """ from breezypythongui import EasyFrame class PanelDemo(EasyFrame): def __init__(self): # Create the main frame EasyFrame.__init__(self, "Panel Demo - v2") # Create the panel for the data dataPanel = self.addPanel(row = 0, column = 0, background = "gray") # Create and add widgets to the data panel dataPanel.addLabel(text = "Label 1", row = 0, column = 0, background = "gray") dataPanel.addTextField(text = "Text1", row = 0, column = 1) dataPanel.addLabel(text = "Label 2", row = 1, column = 0, background = "gray") dataPanel.addTextField(text = "Text2", row = 1, column = 1,) # Create the nested frame for the button panel buttonPanel = self.addPanel(row = 1, column = 0, background = "black") # Create and add buttons to the button panel buttonPanel.addButton(text = "B1", row = 0, column = 0) buttonPanel.addButton(text = "B2", row = 0, column = 1) buttonPanel.addButton(text = "B3", row = 0, column = 2) def main(): """Instantiate and pop up the window.""" PanelDemo().mainloop() if __name__ == "__main__": main()

prompterboxdemo.py

""" File: prompterboxdemo.py """ from breezypythongui import EasyFrame class PrompterBoxDemo(EasyFrame): """Demonstrates the use of prompter boxes.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = "Prompter Box Demo", width = 300, height = 100) self.label = self.addLabel(text = "", row = 0, column = 0, sticky = "NSEW") self.addButton(text = "Username",row = 1, column = 0, command = self.getUserName) def getUserName(self): text = self.prompterBox(title = "Input Dialog", promptString = "Your username:") self.label["text"] = "Hi, " + text + "!" def main(): """Instantiate and pop up the window.""" PrompterBoxDemo().mainloop() if __name__ == "__main__": main()

radiobuttondemo.py

""" File: radiobuttondemo.py """ from breezypythongui import EasyFrame class RadiobuttonDemo(EasyFrame): """Allows the user to place a restaurant order from a set of options.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, "Radio Button Demo") # Add the label, button group, and buttons for meats self.addLabel(text = "Meat", row = 0, column = 0) self.meatGroup = self.addRadiobuttonGroup(row = 1, column = 0, rowspan = 2) defaultRB = self.meatGroup.addRadiobutton(text = "Chicken") self.meatGroup.setSelectedButton(defaultRB) self.meatGroup.addRadiobutton(text = "Beef") # Add the label, button group, and buttons for potatoes self.addLabel(text = "Potato", row = 0, column = 1) self.taterGroup = self.addRadiobuttonGroup(row = 1, column = 1, rowspan = 2) defaultRB = self.taterGroup.addRadiobutton(text = "French fries") self.taterGroup.setSelectedButton(defaultRB) self.taterGroup.addRadiobutton(text = "Baked potato") # Add the label, button group, and buttons for veggies self.addLabel(text = "Vegetable", row = 0, column = 2) self.vegGroup = self.addRadiobuttonGroup(row = 1, column = 2, rowspan = 2) defaultRB = self.vegGroup.addRadiobutton(text = "Applesauce") self.vegGroup.setSelectedButton(defaultRB) self.vegGroup.addRadiobutton(text = "Green beans") self.addButton(text = "Place order", row = 3, column = 0, columnspan = 3, command = self.placeOrder) # Event handler method def placeOrder(self): """Display a message box with the order information.""" message = "" message += self.meatGroup.getSelectedButton()["text"] + "\n\n" message += self.taterGroup.getSelectedButton()["text"] + "\n\n" message += self.vegGroup.getSelectedButton()["text"] self.messageBox(title = "Customer Order", message = message) def main(): """Instantiate and pop up the window.""" RadiobuttonDemo().mainloop() if __name__ == "__main__": main()

rgb.py

""" File: rgb.py """ def rgbToHexString(rgbTriple): """Converts the rgbTriple (R, G, B) to a hex string of the form #RRGGBB.""" hexString = "" for i in rgbTriple: # Iterate through the triple twoDigits = hex(i)[2:] if len(twoDigits) == 1: twoDigits = '0' + twoDigits hexString += twoDigits return '#' + hexString

smokey.gif

textareademo.py

""" File: textareademo.py Compute an investment report, GUI-based version. 1. The inputs are starting investment amount number of years interest rate (an integer percent) 2. The report is displayed in tabular form with a header. 3. Computations and outputs: for each year compute the interest and add it to the investment print a formatted row of results for that year 4. The total investment and interest earned are also displayed. """ from breezypythongui import EasyFrame class TextAreaDemo(EasyFrame): """Demonstrates a multiline text area.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, "Investment Calculator") self.addLabel(text = "Initial amount", row = 0, column = 0) self.addLabel(text = "Number of years", row = 1, column = 0) self.addLabel(text = "Interest rate in %", row = 2, column = 0) self.amount = self.addFloatField(value = 0.0, row = 0, column = 1) self.period = self.addIntegerField(value = 0, row = 1, column = 1) self.rate = self.addIntegerField(value = 0, row = 2, column = 1) self.outputArea = self.addTextArea("", row = 4, column = 0, columnspan = 2, width = 50, height = 15) self.compute = self.addButton(text = "Compute", row = 3, column = 0, columnspan = 2, command = self.compute) # Event handling method. def compute(self): """Computes the investment schedule based on the inputs and outputs the schedule.""" # Obtain and validate the inputs startBalance = self.amount.getNumber() rate = self.rate.getNumber() / 100 years = self.period.getNumber() if startBalance == 0 or rate == 0 or years == 0: return # Set the header for the table result = "%4s%18s%10s%16s\n" % ("Year", "Starting balance", "Interest", "Ending balance") # Compute and append the results for each year totalInterest = 0.0 for year in range(1, years + 1): interest = startBalance * rate endBalance = startBalance + interest result += "%4d%18.2f%10.2f%16.2f\n" % \ (year, startBalance, interest, endBalance) startBalance = endBalance totalInterest += interest # Append the totals for the period result += "Ending balance: $%0.2f\n" % endBalance result += "Total interest earned: $%0.2f\n" % totalInterest # Output the result while preserving read-only status self.outputArea["state"] = "normal" self.outputArea.setText(result) self.outputArea["state"] = "disabled" def main(): """Instantiate and pop up the window.""" TextAreaDemo().mainloop() if __name__ == "__main__": main()

textfielddemo.py

""" File: textfielddemo.py """ from breezypythongui import EasyFrame class TextFieldDemo(EasyFrame): """Converts an input string to uppercase and displays the result.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self) # Label and field for the input self.addLabel(text = "Input", row = 0, column = 0) self.inputField = self.addTextField(text = "", row = 0, column = 1) # Label and field for the output self.addLabel(text = "Output", row = 1, column = 0) self.outputField = self.addTextField(text = "", row = 1, column = 1, state = "readonly") # The command button self.button = self.addButton(text = "Convert", row = 2, column = 0, columnspan = 2, command = self.convert) # The event handling method for the button def convert(self): """Inputs the string, converts it to uppercase, and outputs the result.""" text = self.inputField.getText() result = text.upper() self.outputField.setText(result) def main(): """Instantiate and pop up the window.""" TextFieldDemo().mainloop() if __name__ == "__main__": main()