# a simple pygame example # module pygame free from: http://www.pygame.org # creates nested circles on a yellow background # vegaseat import pygame pygame.init() # create a 300 x 300 pixel display window # the default background is black win = pygame.display.set_mode((300, 300)) # add nice title pygame.display.set_caption("Bull's Eye!") # pygame uses (r, g, b) color tuples white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) yellow = (255, 255, 0) # create a canvas (in memory) to draw on canvas = pygame.Surface(win.get_size()) # fill surface canvas.fill(yellow) center = (150, 150) # draw a black border circle radius = 92 pygame.draw.circle(canvas, black, center, radius) # draw a white circle radius = 90 pygame.draw.circle(canvas, white, center, radius) # draw a red circle that fits into the white one radius = 80 pygame.draw.circle(canvas, red, center, radius) # finally the black bull's eye radius = 10 pygame.draw.circle(canvas, black, center, radius) # transfer canvas to display window at ulc (x=0, y=0) win.blit(canvas, (0, 0)) # update/flip to show on the computer display pygame.display.flip() # event loop and exit conditions (windows titlebar x click) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit
# testing a notebook widget class for Tkinter (modified) # Python 2.5.4 ene import Tkinter as tk class Notebook(object): """ a notebook widget class for Tkinter applications """ def __init__(self, parent): self.active_page = None self.count = 0 self.selected = tk.IntVar(0) # orientation of initial tab (can go 'bottom' too) side = 'top' # new tabs go self.side= 'left' # create notebook's initial page frame self.tab = tk.Frame(parent) self.tab.pack(side=side, fill='both') self.page = tk.Frame(parent) self.page.pack(fill='both') def __call__(self): """ parent page reference """ return self.page def add_page(self, pg, title): """ add a new page to the notebook """ rb = tk.Radiobutton(self.tab, text=title, indicatoron=0, variable=self.selected, value=self.count, command=lambda: self.display_page(pg)) rb.pack(fill='both', side=self.side) # first page is slected by default if not self.active_page: pg.pack(fill='both', expand=True) self.active_page = pg self.count += 1 # returns reference return rb def display_page(self, pg): """ shows selected page, hides former page """ self.active_page.forget() pg.pack(fill='both', expand=True) self.active_page = pg # testing the module if __name__ == '__main__': root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("400x200+100+50") root.title('Testing a Tkinter notebook widget') nb = Notebook(root) # create first page (notice the instance call) page1 = tk.Frame(nb()) nb.add_page(page1, 'page 1') # put something on the page # text entry field, width=width in chars, height=lines text text1 = tk.Text(page1, width=60, height=12, bg='yellow') text1.pack(fill='both') text1.insert(tk.INSERT, ' this is page number 1') # create second page, also has a button page2 = tk.Frame(nb()) nb.add_page(page2, 'page 2') # put something on the page text2 = tk.Text(page2, width=60, height=12, bg='green') text2.pack(fill='both') s1 = ' this is page number 2 \n' s2 = ' Look, I am green! \n' s3 = ' Also, I have a button to click!' text2.insert(tk.INSERT, s1+s2+s3) # just a dummy button button2 = tk.Button(page2, text=' save text to file ') button2.pack(side='left') root.mainloop()
import random import tkinter as tk def Coin_Toss(): try: n = float(enter.get()) if n > 0: label2.config(text='') except ValueError: label2.config(text='Need numeric value') display = "" heads = 0 tails = 0 counter = 0 Heads = "H" Tails = "T" try: while (counter < n): if random.randrange(2): heads += 1 if heads > 0: display = str(display + " " + Heads) label.config(text=display) counter += 1 else: tails += 1 if tails > 0: display = str(display + " " + Tails) label.config(text=display) counter += 1 hep = heads * 100 / n tap = tails * 100 / n h = repr(heads) t = repr(tails) hp = repr(hep) tp = repr(tap) display = display + " " label.config(text=display) display1 = str("The coin landed on heads " + h + " times.") label3.config(text=display1) display2 = str("The coin landed on tails " + t + " times.") label4.config(text=display2) display3 = str("The coin landed on heads " + hp + "% of the time.") label5.config(text=display3) display4 = str("The coin landed on tails " + tp + "% of the time.") label6.config(text=display4) btn.config(text=' End ', command=End) except UnboundLocalError: pass def End(): display = "Thank you for running Coin Toss." label.config(text=display) display = '' label.config(text=display) n = 0 label.config(text='') label2.config(text='') label3.config(text='') label4.config(text='') label5.config(text='') label6.config(text='') btn.config(text=' Run ', command=Coin_Toss) root = tk.Tk() root.title("DevPython Suite") label = tk.Label(root, text='') label1 = tk.Label(root, text='Number of times to flip the coin: ') label2 = tk.Label(root, text='') label3 = tk.Label(root, text='') label4 = tk.Label(root, text='') label5 = tk.Label(root, text='') label6 = tk.Label(root, text='') label0 = tk.Label(root, text='Welcome to the Coin Toss Program') enter = tk.Entry(root) btn = tk.Button(root, text=' Run ', command=Coin_Toss) label0.grid(row=0, column=0) label1.grid(row=1, column=0) enter.grid(row=2,column=0) btn.grid(row=3,column=0) label2.grid(row=4,column=0) label.grid(row=5,column=0) label3.grid(row=6,column=0) label4.grid(row=7,column=0) label5.grid(row=8,column=0) label6.grid(row=9,column=0) enter.focus_set() root.mainloop()
#insert the lines of code in place of the existing code in the lines mentioned import random, time #line 1 message.config(text=display) #lines 41 label2.config(text=display) #line 56 message.config(text='') #line 60 message = tk.Message(root, text='') #line 72 message.grid(row=5,column=0) #line 88 #delete lines 26, 32, 40, 57, 58, & 61
''' Python31 includes the Tkinter Tile extension Ttk. Ttk comes with 17 widgets, 11 of which already exist in Tkinter: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar The 6 new widget classes are: Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview For additional info see the Python27 or Python31 manual: http://gpolo.ath.cx:81/pydoc/library/ttk.html Here the TreeView widget is configured as a multi-column listbox with adjustable column width and column-header-click sorting. Tested with Python3.1 and Tkinter8.5 by vegaseat 17jul2009 ''' import tkinter as tk import tkinter.font as tkFont import tkinter.ttk as ttk class McListBox(object): """use a ttk.TreeView as a multicolumn ListBox""" def __init__(self): self.tree = None self._setup_widgets() self._build_tree() def _setup_widgets(self): s = """\ click on header to sort by that column to change width of column drag boundary """ msg = ttk.Label(wraplength="4i", justify="left", anchor="n", padding=(10, 2, 10, 6), text=s) msg.pack(fill='x') container = ttk.Frame() container.pack(fill='both', expand=True) # create a treeview with dual scrollbars self.tree = ttk.Treeview(columns=element_header, show="headings") vsb = ttk.Scrollbar(orient="vertical", command=self.tree.yview) hsb = ttk.Scrollbar(orient="horizontal", command=self.tree.xview) self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) self.tree.grid(column=0, row=0, sticky='nsew', in_=container) vsb.grid(column=1, row=0, sticky='ns', in_=container) hsb.grid(column=0, row=1, sticky='ew', in_=container) container.grid_columnconfigure(0, weight=1) container.grid_rowconfigure(0, weight=1) def _build_tree(self): for col in element_header: self.tree.heading(col, text=col.title(), command=lambda c=col: sortby(self.tree, c, 0)) # adjust the column's width to the header string self.tree.column(col, width=tkFont.Font().measure(col.title())) for item in element_list: self.tree.insert('', 'end', values=item) # adjust column's width if necessary to fit each value for ix, val in enumerate(item): col_w = tkFont.Font().measure(val) if self.tree.column(element_header[ix], width=None) < col_w: self.tree.column(element_header[ix], width=col_w) def isnumeric(s): """test if a string is numeric""" for c in s: if c in "1234567890-.": numeric = True else: return False return numeric def change_numeric(data): """if the data to be sorted is numeric change to float""" new_data = [] if isnumeric(data[0][0]): # change child to a float for child, col in data: new_data.append((float(child), col)) return new_data return data def sortby(tree, col, descending): """sort tree contents when a column header is clicked on""" # grab values to sort data = [(tree.set(child, col), child) for child in tree.get_children('')] # if the data to be sorted is numeric change to float data = change_numeric(data) # now sort the data in place data.sort(reverse=descending) for ix, item in enumerate(data): tree.move(item[1], '', ix) # switch the heading so that it will sort in the opposite direction tree.heading(col, command=lambda col=col: sortby(tree, col, int(not descending))) # the test data ... element_header = ['symbol', 'name', 'atomic weight', 'melt (K)', 'boil (K)'] element_list = [ ('H', 'Hydrogen', '1.00794', '13.81', '20.28') , ('He', 'Helium', '4.00260', '0.95', '4.216') , ('Li', 'Lithium', '6.941', '453.7', '1615') , ('Be', 'Beryllium', '9.01218', '1560', '3243') , ('B', 'Boron', '10.811', '2365', '4275') , ('C', 'Carbon', '12.011', '3825', '5100') , ('N', 'Nitrogen', '14.0067', '63.15', '77.344') , ('O', 'Oxygen', '15.9994', '54.8', '90.188') , ('F', 'Fluorine', '18.99840', '53.65', '85.0') ] root = tk.Tk() root.wm_title("ttk.TreeView as multicolumn ListBox") mc_listbox = McListBox() root.mainloop()
# simple PyQT window with two buttons and one label # to test pop-up dialogs for getting name and age # QInputDialog.getText(parent, title, label, echo=QLineEdit.Normal, # text=QString(), flags=0) # QInputDialog.getInt(parent, title, label, value, minValue, # maxValue, step=1, flags=0) # http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qinputdialog.html import sys # use this import option for simplicity from PyQt4.QtCore import * from PyQt4.QtGui import * class MyForm(QWidget): def __init__(self): QWidget.__init__(self) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 320, 100) self.setWindowTitle("Testing dialog input") self.name = "" btn_name = QPushButton("Get Name") self.connect(btn_name, SIGNAL("clicked()"), self.get_name) btn_age = QPushButton("Get Age") # bind the button click to a function reference self.connect(btn_age, SIGNAL("clicked()"), self.get_age) self.label = QLabel("------------------") # use grid layout for the widgets grid = QGridLayout() # addWidget(widget, row, column, rowSpan=1, columnSpan=1) grid.addWidget(btn_name, 0, 0) grid.addWidget(btn_age, 1, 0) # this will span the label over 3 columns grid.addWidget(self.label, 2, 0, 1, 3) self.setLayout(grid) def get_name(self): self.name, ok = QInputDialog.getText(self, self.tr("Name"), self.tr("Enter your name:")) self.show_result(ok) def get_age(self): # initial age 0, limit between 1 and 120 self.age, ok = QInputDialog.getInteger(self, self.tr("Age"), self.tr("Enter your age:"), 0, 1, 120) self.show_result(ok) def show_result(self, ok): if ok and self.name and str(self.age): s = "%s you are %s old" % (self.name, self.age) elif ok and self.name and not str(self.age): s = self.name else: s = str(self.age) self.label.setText(s) app = QApplication(sys.argv) form = MyForm() form.show() app.exec_()
# Python GUI toolkit Tkinter has 3 different data input dialogs: # tkSimpleDialog.askstring(title, prompt [,options]) # tkSimpleDialog.askinteger(title, prompt [,options]) # tkSimpleDialog.askfloat(title, prompt [,options]) # does error trapping with int and float, also optional max/min # there is also an initialvalue=parameter try: # for Python2 import Tkinter as tk import tkSimpleDialog as tksd except ImportError: # for Python3 import tkinter as tk import tkinter.simpledialog as tksd root = tk.Tk() # parent=root needed to put dialog window on top of parent root window mystr = tksd.askstring("Dialog (String)", "Enter your name:", parent=root) print(mystr) age = tksd.askinteger("Dialog (Integer)", "Enter your age:", parent=root, minvalue=0, maxvalue=120) print(age) pay = tksd.askfloat("Dialog (Float)", "Enter your annual pay:", parent=root, minvalue=1000) print(pay) root.mainloop() # optional help help(tksd)
# PyQT's QLabel widget can display html formatted text import sys # use this import option for simplicity from PyQt4.QtCore import * from PyQt4.QtGui import * class MyForm(QWidget): def __init__(self, html_text): QWidget.__init__(self) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 320, 100) self.setWindowTitle("html formatted text") self.label = QLabel(html_text) # use grid layout grid = QGridLayout() # addWidget(widget, row, column, rowSpan=1, columnSpan=1) grid.addWidget(self.label, 0, 0) self.setLayout(grid) # color is in hex format "#RRGGBB" html_text = """\ <font face="Times New Roman" size=7 color="#0000FF"> Example of <b>bold</b> html formatted text in blue </font> """ app = QApplication(sys.argv) form = MyForm(html_text) form.show() app.exec_()
# experiments with module pygame # free from: http://www.pygame.org/ # load and display an image using pygame and Tkinter's file dialog import pygame as pg # initialize pygame pg.init() #---------- uses Tkinter to open an image filename ------------------ import Tkinter as tk import tkFileDialog as tkfd root = tk.Tk() root.withdraw() dirname = tkfd.askdirectory() mask = [("GIF and JPEG files","*.gif *.jpg")] image_file = tkfd.askopenfilename(initialdir=dirname, filetypes=mask) #-------------------------------------------------------------------- # RGB color tuple used by pygame white = (255, 255, 255) # create a 300x300 white screen screen = pg.display.set_mode((300,300)) screen.fill(white) # load the image from a file image = pg.image.load(image_file) # draw image, position the image ulc at x=50, y=20 screen.blit(image, (50, 20)) # nothing gets displayed until one updates the screen pg.display.flip() # start event loop and wait until # the user clicks on the window corner x while True: for event in pg.event.get(): if event.type == pg.QUIT: raise SystemExit
# pqt_gridlayout1.py # start of small calculator import sys # simple general import from PyQt4.QtCore import * from PyQt4.QtGui import * class GridLayout(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle('grid layout') bt_names = ['Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+'] grid = QGridLayout() pos = [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3 ), (4, 0), (4, 1), (4, 2), (4, 3)] j = 0 for b in bt_names: button = QPushButton(b) if j == 2: # addWidget(QWidget, row, column, rowSpan, columnSpan) grid.addWidget(QLabel(''), 0, 2) else: grid.addWidget(button, pos[j][0], pos[j][1]) j = j + 1 self.setLayout(grid) app = QApplication(sys.argv) qb = GridLayout() qb.show() sys.exit(app.exec_())
| DaniWeb Message | |
| Cancel Changes | |