# use PyQT's QTableView and QAbstractTableModel # to present tabular data # allow sorting by clicking on the header title # tested with Python 3.1.1 and PyQT 4.5.2 # ene import operator from PyQt4.QtCore import * from PyQt4.QtGui import * class MyWindow(QWidget): def __init__(self, data_list, header, *args): QWidget.__init__(self, *args) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 200, 420, 250) self.setWindowTitle("Exploring PyQT's QTableView") table_model = MyTableModel(self, data_list, header) table_view = QTableView() table_view.setModel(table_model) # enable sorting table_view.setSortingEnabled(True) layout = QVBoxLayout(self) layout.addWidget(table_view) self.setLayout(layout) class MyTableModel(QAbstractTableModel): def __init__(self, parent, mylist, header, *args): QAbstractTableModel.__init__(self, parent, *args) self.mylist = mylist self.header = header def rowCount(self, parent): return len(self.mylist) def columnCount(self, parent): return len(self.mylist[0]) def data(self, index, role): if not index.isValid(): return QVariant() elif role != Qt.DisplayRole: return QVariant() return QVariant(self.mylist[index.row()][index.column()]) def headerData(self, col, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return QVariant(self.header[col]) return QVariant() def sort(self, col, order): """sort table by given column number col""" self.emit(SIGNAL("layoutAboutToBeChanged()")) self.mylist = sorted(self.mylist, key=operator.itemgetter(col)) if order == Qt.DescendingOrder: self.mylist.reverse() self.emit(SIGNAL("layoutChanged()")) header = ['First Name', 'Last Name', 'Age', 'Weight'] # a list of (name, age, weight) tuples data_list = [ ('Heidi', 'Kalumpa', '36', '127'), ('Frank', 'Maruco', '27', '234'), ('Larry', 'Pestraus', '19', '315'), ('Serge', 'Romanowski', '59', '147'), ('Carolus', 'Arm', '94', '102'), ('Michel', 'Sargnagel', '21', '175') ] app = QApplication([]) win = MyWindow(data_list, header) win.show() app.exec_()
# adding font and color to PyQT's QLabel widget text # vegaseat 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("font and color") text = " QLabel text with font and color " label = QLabel(text) # QFont(family, pointSize, weight, italic) # weight QFont.Light=25, QFont.Normal=50, QFont.Bold=75 # pointSize=12, weight=50, italic=False by default font = QFont("Times", 32, QFont.Bold, True) label.setFont(font) # set the foreground and background colors of the label fg = "QLabel {color:red}" bg = "QLabel {background-color:yellow}" label.setStyleSheet( fg+bg ) # use grid layout grid = QGridLayout() # addWidget(widget, row, column, rowSpan=1, columnSpan=1) grid.addWidget(label) self.setLayout(grid) app = QApplication([]) form = MyForm() form.show() app.exec_()
# experiments with module pygame # bounce a red ball whose image is stored in this code # pygame from: http://www.pygame.org/ # win binary installed: pygame-1.9.1.win32-py3.1.msi # tested with Python 3.1.1 and Pygame 1.9.1 # vegaseat 14sep2009 import pygame as pg import base64 """ # use this Python3 program to create a base64 encoded image string # (base64 encoding produces a readable string from a binary image) # then copy and paste the result into your pygame program ... import base64 gif_file = "ball_r.gif" gif_bytes = open(gif_file, 'rb').read() b64_bytes = base64.encodebytes(gif_bytes) # decode <class 'bytes'> bytestring to string b64_str = b64_bytes.decode("utf8") print( "gif64='''\\\n" + b64_str + "'''" ) """ gif64='''\ R0lGODlhQABAAPcAACEBAY8DA9wQILcED1ECAqMECOsaL8oKGTgBAXADA5kEBeQVJ8EIFK0EC+wg NS8BAWUCAtMOH0gCAoQDAykBAZkEBNwSJsEGEFsCAq0ECOwdNdMMGkABAXoDA6MEBuUXLsoJFbcE DPIgNQAAAJ0FBAAAAAAAAAAAAAAABQAAAAAAAAAAAPEGCt0FBQQAAAAAAF4CBAkAAN8FBVUCAgAA AgAAAAAAAAAAAAEBgAAAAQUAAwIC7gAAKt0FBQUBZgAAAAAABgAAAAAAAAAAAAsAAN4FBQQAAAAA AOgPDmoCAu8GBlUCAmoDBwgAAOsFBVUCAvIGRfIGDfMHz/IGOhgGZXUDA+sFBVUCAugMoQoCwuEH 0VYCNgACBQAAAAUAAAAAAAACAwAAAAAAAAAAAF2IVdsGDAgFygz4PwssCD0CHwpqGQAAAAII4AAA AAAAH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VtCchCFGVoFrsDn0QHa29dehAgvA6KMGCyRgYVsFZUjXdsmxN9oAPsZ4mggXSHChQAgk wOJyOi63gQNNNjmBeWwRoB2Woq3oII9OpqmbCAeUmFGVtzEo13IFmKbmnXkZ0AF1DxmZpHIqjlZa l3iOSMBFN9bW3YZkVsAAoYQmQFxBKMY555l0QYjnplzNmGBSGHx2aYdkzrUAp5tCeWhHCrK3o4qh ef+QG6R4CoABTXBi6t9tCnxIa5dfDoQiY/1tpxxpv+KpQQYcJCWBhor6F1oFTKLa5YgpASAmrJZu GGCyMDqwgWAAYFAVdw5ime5/dlmr7AIYnGXuoq8mN1oFB0ToroRBCgRBtEjWW9dW+6YZVgL+Hksm rPfmWzCMHyAMwL9XphvtcgyI8LCTQEpa7nr21ruhXeCqaQEGAomJLrfuAViyhBqMO9CzKu44Z20h vOykCCG4BsCw6DZ4cwMbD+hABggMliuDWB7J3qxFgxhsghSvXObNPOosH5AQLGRkzeqGHF/U4pHY FgdW0tXdn8ltQLDWqYkQgM8CJXqlyKM9SjZvQQ7/qa2GQavdYQVEw71mCFKytLR3a7v3wd6n5bXn cEaOqm6HYxuuF5slPrW4pdsFQDLkeu35VEKVG0vvch+S3tsAh1oEVXZKkmppfJp3vBJHDklgZeC7 6m24Bp6qBdFAfjKtOuQOXLCqTGjduF60ozYXNYUWym7QfiCvXlsDWtd3X41T/kw73h4E8GLBIlhw 33DHV4Q24GaK5muM4OEl7vgW5QfAfou5WFVGtzXe5IUBBjrPawozmwQsyF7tydxzDLAXvvgmAJZZ oP8y0hnkoKsC9wuPvrSigQu0RjjwQ1BEErOYI31HX6ihoGo0AIIAmGWB5NsgleBile5QK4Z86YoG Wj5QGfNskEgqNEhHpEKVDoXgAyLQGFd64wADLOAAHijLWXBYGB02pSZSyclO8LUAoAjlAkU5ikq8 yLskMuUgHgGJSBJAkpOkZCVu5CIbL6KSBxgxLWvco0sCAgA7 ''' # encode string to <class 'bytes'>, needed for Python3 # comment out if you are using Python2 gif64 = gif64.encode("utf8") # convert back to a binary image to save to a file in the working directory ball = base64.b64decode(gif64) fout = open("ball_r.gif","wb") fout.write(ball) fout.close() # initialize pygame pg.init() # now you can use the gif file you just saved image_file = "ball_r.gif" # image moves [x, y] at a time im_dir = [2, 1] # pygame uses an RGB color tuple black = (0,0,0) # screen width and height sw = 600 sh = 480 # create a screen screen = pg.display.set_mode((sw, sh)) # give the screen a title pg.display.set_caption('bouncing ball (press escape to exit)') # load the ball image file image = pg.image.load(image_file).convert() # get the rectangle that the image occupies im_rect = image.get_rect() # the event loop also loops the animation code while True: pg.event.pump() keyinput = pg.key.get_pressed() # exit on corner 'x' click or escape key press if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT): raise SystemExit # set the move im_rect = im_rect.move(im_dir) # detect the boundaries and change directions # left/right boundaries are 0 to sreen width if im_rect.left < 0 or im_rect.right > sw: im_dir[0] = -im_dir[0] # top/bottom boundaries are 0 to screen height if im_rect.top < 0 or im_rect.bottom > sh: im_dir[1] = -im_dir[1] # this erases the old sreen with black screen.fill(black) # put the image on the screen screen.blit(image, im_rect) # update screen pg.display.flip()
# create a resizable pygame window # tested with Python 3.1.1 and Pygame 1.9.1 # vegaseat import pygame as pg def create_window(width, height): """create a width x height resizable window/frame""" win = pg.display.set_mode((width, height), pg.RESIZABLE) # optional fill bg red, default is black win.fill((255, 0, 0)) # optional title info sf = "size x=%s y=%s" % (width, height) pg.display.set_caption(sf) # any extra code here ... # draw a white circle white = (255, 255, 255) # center can be fixed or calculated for resize center = (150, 150) radius = 100 pg.draw.circle(win, white, center, radius) pg.display.flip() return win pg.init() width = 300 height = 200 win = create_window(width, height) # event loop and exit conditions (windows titlebar x click) while True: for event in pg.event.get(): if event.type == pg.VIDEORESIZE: width, height = event.size # redraw win in new size win = create_window(width, height) print(win.get_size()) # test if event.type == pg.QUIT: raise SystemExit
# using Tkinter's Optionmenu() as a combobox try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk def select(): sf = "value is %s" % var.get() root.title(sf) # optional color = var.get() root['bg'] = color root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150)) root.title("tk.Optionmenu as combobox") var = tk.StringVar(root) # initial value var.set('red') choices = ['red', 'green', 'blue', 'yellow','white', 'magenta'] option = tk.OptionMenu(root, var, *choices) option.pack(side='left', padx=10, pady=10) button = tk.Button(root, text="check value slected", command=select) button.pack(side='left', padx=20, pady=10) root.mainloop()
# explore the ttk.Progressbar of the Tkinter module ttk # ttk is included with Python 3.1.1 # vegaseat import tkinter as tk from tkinter import ttk def click(event): # can be a float increment = 3.4 pbar.step(increment) root = tk.Tk() root.title('ttk.Progressbar') pbar = ttk.Progressbar(root, length=300) pbar.pack(padx=5, pady=5) btn = tk.Button(root, text="Click to advance progress bar") # bind to left mouse button click btn.bind("<Button-1>", click) btn.pack(pady=10) root.mainloop()
# draw cones in space # press the right mouse button and use cursor to rotate the object # experiments with visual Python (VPython) from: http://vpython.org/ # used VPython-Win-Py2.6-5.12.exe for Python26 # needs and comes with numpy """ cone(pos=(0,0,0), axis=(1,0,0), radius=1, color=(0,0,0)) color (red, green, blue) color values 0.0 to 1.0 default is white = (1,1,1) """ import visual as vs vs.scene.width = 500 vs.scene.height = 500 vs.scene.title = "draw 3 cones (drag with right mouse button)" # avoid autoscale (autoscale default=True) vs.scene.autoscale = False # axis x=8 points right cone1 = vs.cone(pos=(0,0,0), axis=(8,0,0), radius=4) cone1.color = vs.color.green # axis x=-8 points left cone2 = vs.cone(pos=(0,0,0), axis=(-8,0,0), radius=4) cone2.color = vs.color.red # pos y=-6 is below center and axis y=2.4 points up from there cone3 = vs.cone(pos=(0,-6,0), axis=(0,2.4,0), radius=4) cone3.color = (0.0, 0.9, 1.0)
# create a window with a button and click event using ironpython # ironpython gives access to the Windows .NET or Linux Mono libraries # download ironpython from: # http://www.codeplex.com/ironpython # tutorial at: # http://www.zetcode.com/tutorials/ironpythontutorial/ # # to distinguish the filename from normal Python use prefix ip_ # if you save this file as "ip_buttonWin1.py" # compile it with something like: # C:\IronPython 2.6\ipy.exe "ip_buttonWin1.py" # # clr -> Common Language Runtime import clr clr.AddReference("System.Windows.Forms") clr.AddReference("System.Drawing") from System.Windows.Forms import Application, Form, Button, ToolTip from System.Drawing import Size, Point class IForm(Form): def __init__(self): # set form title, position, size self.Text = 'Button' self.CenterToScreen() self.Size = Size(300, 150) btn = Button() btn.Parent = self btn.Text = "Quit" btn.Location = Point(50, 50) # click on the button to call OnClick() btn.Click += self.OnClick # mouse over button calls OnEnter() btn.MouseEnter += self.OnEnter # optional tooltip tooltip = ToolTip() # tooltip for the button tooltip.SetToolTip(btn, "Don't be a Quitter") def OnClick(self, sender, args): self.Close() def OnEnter(self, sender, args): #print sender, type(sender) self.Text = "mouse entered button area" Application.Run(IForm())
# explore Tkinter and PIL to create a list of photos # that can be displayed as thumbnails # tested with Python25 by vegaseat import Tkinter as tk from PIL import ImageTk, Image import glob import random # make sure you have a folder with some jpeg pictures folder = "./Pics_jpg" # create a list of .jpg images that are in this folder pic_list = glob.glob(folder+'/*.jpg') root = tk.Tk() root.title(folder) label_list = [] photo_list = [] for pathname in pic_list: image = Image.open(pathname) # create a thumbnail of each image # width=100 height=150 image.thumbnail((100, 150), Image.ANTIALIAS) # convert to something Tkinter can handle photo = ImageTk.PhotoImage(image) # the photo list is needed for labels to retain photos! photo_list.append(photo) label_list.append(tk.Label(image=photo)) # optionally random shuffle the label_list #random.shuffle(label_list) # display the thumbnails in rows of pics_per_row pictures pics_per_row = 4 row = col = 0 for label in label_list: label.grid(row=row, column=col) col += 1 if col >= pics_per_row: col = 0 row += 1 root.mainloop()
| DaniWeb Message | |
| Cancel Changes | |