| | |
Python GUI Programming
![]() |
Contributions should have an emphasis on comparing the various GUI toolkits, showing example code and solutions to problems.
The example code should be usable as templates, so folks get a feel for the toolkit and can use those examples/templates as a basis for more complex programs.
Again, don't clutter up the sticky with questions. Ask question in the regular forum.
The example code should be usable as templates, so folks get a feel for the toolkit and can use those examples/templates as a basis for more complex programs.
Again, don't clutter up the sticky with questions. Ask question in the regular forum.
May 'the Google' be with you!
Here's an example of a basic window frame in pyQT.
You can get pyQT from here: http://www.riverbankcomputing.co.uk/.../pyqt/download
You can get pyQT from here: http://www.riverbankcomputing.co.uk/.../pyqt/download
python Syntax (Toggle Plain Text)
# Code Example: Display a window in PyQt4 # Python 2.6 with PyQt 4 import sys from PyQt4 import QtGui class MainFrame(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setWindowTitle("Window title") # title self.resize(1024, 768) # size self.setMinimumSize(800, 600) # minimum size self.move(0, 0) # position window frame at top left if __name__ == "__main__": app = QtGui.QApplication(sys.argv) frame = MainFrame() frame.show() exit_code = app.exec_() sys.exit(exit_code)
Last edited by scru; May 8th, 2009 at 3:04 pm.
This next pyQT example builds on the last and incorporates a simple box layout used with a button and a canvas. It also shows how to hook up a button event.
python Syntax (Toggle Plain Text)
# Code Example: Display a window with a button, icon and canvas in PyQt4 # Python 2.6 with PyQt 4 # This example build on the last one by adding a button, changing the # window icon, and adding a canvas where we can draw some shapes. import sys from PyQt4 import QtGui, QtCore class MainFrame(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setWindowTitle("Window title") # title self.resize(1024, 768) # size self.setMinimumSize(800, 600) # minimum size self.move(0, 0) # position window frame at top left # Adding the icon: self.setWindowIcon(QtGui.QIcon("myicon.png")) # Set the central widget for the main window cwidget = QtGui.QWidget(self) # Set up a layout for the button and canvas: layout = QtGui.QVBoxLayout() #vertical box layout #layout = QtGui.QHBoxLayout() #horizontal box layout self.add_button(layout) self.add_canvas(layout) cwidget.setLayout(layout) self.setCentralWidget(cwidget) # Now set up the shapes that we draw on each button click # get the button back from the layout button = layout.itemAt(0).widget() # Create objects used for drawing sol_pen = QtGui.QPen(QtGui.QColor("black")) dot_pen = QtGui.QPen(QtGui.QColor("black")) dot_pen.setStyle(QtCore.Qt.DotLine) dash_pen = QtGui.QPen(QtGui.QColor("black")) dash_pen.setStyle(QtCore.Qt.DashLine) r_brush = QtGui.QBrush(QtGui.QColor("red")) g_brush = QtGui.QBrush(QtGui.QColor("green")) b_brush = QtGui.QBrush(QtGui.QColor("blue")) triangle = QtGui.QPolygonF() triangle.append(QtCore.QPointF(100, 50)) triangle.append(QtCore.QPointF(200, 200)) triangle.append(QtCore.QPointF(0, 200)) self.scene_data = [] # add data for drawing circle #self.scene.addEllipse(0, 0, 150, 150, sol_pen, r_brush) #x, y, w, h etc self.scene_data.append({'routine':self.scene.addEllipse, 'args':(0,0,150,150,sol_pen,r_brush), 'z': 0, #z-index 'next': "Draw Rectangle"}) # add data for drawing square #self.scene.addRect(100, 100, 150, 150, dot_pen, g_brush) #x, y, w, h etc self.scene_data.append({'routine':self.scene.addRect, 'args':(100,100,150,150, dot_pen, g_brush), 'z':1, 'next': "Draw Triangle."}) # add data for drawing triangle #self.scene.addPolygon(triangle, dash_pen, b_brush) self.scene_data.append({'routine':self.scene.addPolygon, 'z':2, 'args':(triangle, dash_pen, b_brush)}) # Set up self.draw_next_item to fire when button is clicked. self.connect(button, QtCore.SIGNAL("clicked()"), self.draw_next_item) def add_button(self, layout): """Create a button and then add it to the layout.""" button = QtGui.QPushButton("Draw Circle") layout.addWidget(button) def add_canvas(self, layout): """Create a canvas and then add it to the layout.""" canvas = QtGui.QGraphicsView() layout.addWidget(canvas) # Now create a graphics scene to draw shapes to. # Now remember to keep a reference to GraphicsScene for as long as # you're using it, because unlike widgets, these are automatically # destroyed when they lose reference count self.scene = QtGui.QGraphicsScene() canvas.setScene(self.scene) def draw_next_item(self): # get the button. could've just saved as self.button, but I wanted to # show how it could be done this way button = self.centralWidget().layout().itemAt(0).widget() d = self.scene_data.pop(0) # get first item item = d['routine'](*d['args']) # just a little python magic item.setZValue(d['z']) if len(self.scene_data): # more stuff to draw, set button label button.setText(d['next']) else: # no more left, disable button button.setText("No more shapes!") button.setDisabled(True) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) frame = MainFrame() frame.show() exit_code = app.exec_() sys.exit(exit_code)
Last edited by scru; May 8th, 2009 at 4:57 pm.
Here is a comparison of some common Python GUI toolkits. These were created on my Ubuntu/Linux machine, because I could never get PyGTK to go on my Windows Vista machine. I followed the installation routine carefully, but there was always a dll missing, or an entry point wasn't found, or a version missmatch, so I gave up. GTK and PyGTK are more natural on Linux.
Let's take a look at typical PyGTK code:
The same test program using PyQT, PyQT installs easily on Windows and Linux machines:
Here is a simplified wxPython program (could have used a class):
Last not least Tkinter, which usually ships with Python:
Editor's note:
The first line in snee's code
#!/usr/bin/env python
tells Linux where it can find the Python interpreter
it is simply ignored on Windows machines.
Let's take a look at typical PyGTK code:
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # display an image using PyGTK + GTK import pygtk pygtk.require('2.0') import gtk class ShowImage(object): def __init__(self): # create the main window, and window = gtk.Window(gtk.WINDOW_TOPLEVEL) # attach destroy signal to terminate the application window.connect("destroy", lambda w: gtk.main_quit()) window.set_border_width(10) window.show() # a horizontal box to hold the buttons hbox = gtk.HBox() hbox.show() window.add(hbox) # pick an image file you have in the working directory, or give # the full path, can be a .jpg, .png, ,gif, .bmp image file # (filenames are case sensitive on Ubuntu/Linux) image_file = "LAKE2.gif" image = gtk.Image() image.set_from_file(image_file) image.show() # create a button to contain the image widget # auto adjusts to image size button = gtk.Button() button.add(image) button.show() hbox.pack_start(button) ShowImage() gtk.main()
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # display an image using PyQT import sys from PyQt4 import QtGui class MyImage(QtGui.QWidget): def __init__(self, parent, width, height): QtGui.QWidget.__init__(self, parent) # pick an image file you have in the working directory, or give # the full path, can be a .jpg, .png, ,gif, .bmp image file # (filenames are case sensitive on Ubuntu/Linux) image_file = "LAKE2.gif" image = QtGui.QPixmap(image_file) # show the image name in the title self.setWindowTitle(image_file) # use a label to display the image in label = QtGui.QLabel(self) label.setGeometry(10, 10, width, height) label.setPixmap(image) app = QtGui.QApplication(sys.argv) # assume image is about 400x300 pixels in size width = 400 height = 300 w = MyImage(None, width, height) # setGeometry(x, y, width, height) ULC coordinates x.y w.setGeometry(100, 100, width+20, height+20) w.show() app.exec_()
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # display an image using wxPython import wx app = wx.App(0) frame = wx.Frame(None, wx.ID_ANY, "Show an image file") # pick an image file you have in the working directory, or give # the full path, can be a .jpg, .png, ,gif, .bmp image file # (filenames are case sensitive on Ubuntu/Linux) image_file = 'LAKE2.gif' image = wx.Bitmap(image_file) image_width = image.GetWidth() image_height = image.GetHeight() # set frame size to image size frame.SetClientSize((image_width, image_height)) # show the image as static bitmap wx.StaticBitmap(frame, wx.ID_ANY, image) # show the image name in the title frame.SetTitle(image_file) frame.Show() app.MainLoop()
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # display an image using Tkinter import Tkinter as tk root = tk.Tk() # pick an image file you have in your working directory # or use full path, Tkinter only reads .gif image files # (filenames are case sensitive on Ubuntu/Linux) image_file = "LAKE2.gif" photo = tk.PhotoImage(file=image_file) root.title(image_file) # put the image on a typical widget label = tk.Label(root,image=photo) label.pack(padx=5, pady=5) root.mainloop()
The first line in snee's code
#!/usr/bin/env python
tells Linux where it can find the Python interpreter
it is simply ignored on Windows machines.
Last edited by vegaseat; May 11th, 2009 at 1:59 pm. Reason: Linux note
No one died when Clinton lied.
Thanks for the sample code and the nice picture. I thought I should add pyglet, which is an audio-visual module using GL and FFmpeg available for Windows and Unix systems ...
Pyglet is not a full GUI toolkit, but has its strength in audio and video presentations.
python Syntax (Toggle Plain Text)
# show an image using pyglet # download pyglet from: http://www.pyglet.org/download.html # (the event handler is attached via a function decorator) import pyglet # pick an image file you have in the working directory, or give # the full path, can be a .jpg, .png, ,gif, .bmp image file # (I understand filenames are case sensitive on Linux) image_file = 'LAKE2.gif' img = pyglet.image.load(image_file) # create and size the window to the picture size + # a small frame around it w = img.width + 10 h = img.height + 10 win = pyglet.window.Window(width=w, height=h) # give the window a title win.set_caption(image_file) @win.event def on_draw(): win.clear() # draw image in window at coordinates x=5, y=5 # note that coordinates start at lower left corner img.blit(5, 5) pyglet.app.run()
May 'the Google' be with you!
PyQT was no problem on Windows XP. I downloaded and installed:
http://www.riverbankcomputing.com/st...pl-4.4.3-1.exe
The cumbersome split between QtCore and QtGui is made simpler if you use the import statements show below ...
This little PyQT template can be used for quite a few basic programs. Now, if I could introduce some color! Hey, I am a slow learner!
http://www.riverbankcomputing.com/st...pl-4.4.3-1.exe
The cumbersome split between QtCore and QtGui is made simpler if you use the import statements show below ...
python Syntax (Toggle Plain Text)
# a simple window using PyQT # with 2 buttons and a label import sys # might be easier to use this import option 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("A simple window") # use a grid layout for the widgets grid = QGridLayout() btn_hello = QPushButton("Hello") # bind the button click to a function reference self.connect(btn_hello, SIGNAL("clicked()"), self.on_click) btn_quit = QPushButton("Quit") self.connect(btn_quit, SIGNAL("clicked()"), app.quit) self.label = QLabel("-------------") # addWidget(widget, row, column, rowSpan=1, columnSpan=1) grid.addWidget(btn_hello, 0, 0) # this will span the label over 3 columns grid.addWidget(self.label, 1, 0, 1, 3) grid.addWidget(btn_quit, 2, 0) self.setLayout(grid) def on_click(self): self.label.setText("You clicked the Hello button!") app = QApplication(sys.argv) form = MyForm() form.show() app.exec_()
Last edited by vegaseat; May 11th, 2009 at 2:23 pm. Reason: btn
May 'the Google' be with you!
One of my standard test programs for any GUI toolkit, creating, loading a listbox and selecting an item. Here is the PyQT code ...
I do miss the colors. Here is the corresponding wxPython code with some colors added ...
The wx.GridBagSizer() seems to be more complex.
python Syntax (Toggle Plain Text)
# a simple window using PyQT # with a button and a listbox to load and select import sys # might be easier to use this import option from PyQt4.QtCore import * from PyQt4.QtGui import * class MyForm(QWidget): def __init__(self, name_list): QWidget.__init__(self) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 300, 220) self.setWindowTitle("Load the listbox first") # make name_list available for methods self.name_list = name_list # use a grid layout for the widgets grid = QGridLayout() btn_load = QPushButton("Load List") # bind the button click to a function reference self.connect(btn_load, SIGNAL("clicked()"), self.on_click) self.listbox = QListWidget() self.connect(self.listbox, SIGNAL("itemSelectionChanged()"), self.on_select) # addWidget(widget, row, column, rowSpan, columnSpan) grid.addWidget(btn_load, 0, 0, 1, 1) # listbox spans over 5 rows and 2 columns grid.addWidget(self.listbox, 1, 0, 5, 2) self.setLayout(grid) def on_click(self): """the load button has been clicked, load the listbox""" self.listbox.addItems(self.name_list) def on_select(self): """an item in the listbox has been clicked/selected""" selected_name = self.listbox.selectedItems()[0].text() self.setWindowTitle(selected_name) name_list = [ "Erich Meitinger", "Udo Baus", "Jens Klein", "Bjorn Bork", "Heidrun Lovelace", "Klaus Abraham", "Ulla Jorgens", "Volger Jenkings", "Helmut Schmidt", "Freja Larse", "Larry Orkan", "Andreas Mauser", "Harry Heimlich" ] app = QApplication(sys.argv) form = MyForm(name_list) form.show() app.exec_()
python Syntax (Toggle Plain Text)
# a simple window using wxPython # with a button and a listbox to load and select import wx class MyFrame(wx.Frame): def __init__(self, name_list): wx.Frame.__init__(self, parent=None) self.SetBackgroundColour("green") # ah, color! self.SetTitle('Load the listbox first') # make name_list available for methods self.name_list = name_list # use a grid layout for the widgets grid = wx.GridBagSizer() self.btn_load = wx.Button(self, -1, "Load List") # bind the button click to a function reference self.btn_load.Bind(wx.EVT_BUTTON, self.on_click) self.listbox = wx.ListBox(self) self.listbox.SetBackgroundColour("yellow") self.listbox.Bind(wx.EVT_LISTBOX, self.on_select) # Add(widget, pos=(row, column), span=(rowspan, columnspan)) grid.Add(self.btn_load, pos=(0, 0), flag=wx.ALL, border=5) # add a 180 pixel wide spacer grid.Add((180, 0), pos=(0, 1)) grid.Add(self.listbox, pos=(1,0), span=(10,2), flag=wx.ALL|wx.EXPAND, border=5) self.SetSizerAndFit(grid) def on_click(self, event): """the load button has been clicked, load the listbox""" self.listbox.Set(self.name_list) def on_select(self, event): """an item in the listbox has been clicked/selected""" selected_name = self.listbox.GetStringSelection() self.SetTitle(selected_name) name_list = [ "Erich Meitinger", "Udo Baus", "Jens Klein", "Bjorn Bork", "Heidrun Lovelace", "Klaus Abraham", "Ulla Jorgens", "Volger Jenkings", "Helmut Schmidt", "Freja Larse", "Larry Orkan", "Andreas Mauser", "Harry Heimlich" ] app = wx.App(0) MyFrame(name_list).Show() app.MainLoop()
Last edited by vegaseat; May 11th, 2009 at 9:18 pm. Reason: wx code added
May 'the Google' be with you!
I got PyQT4 istalled and working on my Vista computer. Here is an example of my first program:
python Syntax (Toggle Plain Text)
# display a bunch of random circles using PyQT4 import random import sys # pray for minimal namespace conflicts from PyQt4.QtCore import * from PyQt4.QtGui import * class DrawPoints(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(200, 200, 400, 400) self.setWindowTitle('Draw random Circles') def paintEvent(self, event): painter = QPainter() painter.begin(self) # pen sets the edge color of the circles painter.setPen(Qt.black) w = self.size().width() h = self.size().height() # draw 150 circles of random sizes, locations and colors for i in range(150): # color uses red, green, blue values (0 to 255) r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) # brush sets the fill color of the circles painter.setBrush(QBrush(QColor(r, g, b))) # get center coordinates x,y of the circle x = random.randint(1, w-1) y = random.randint(1, h-1) # get the radius of the circle radius = random.randint(5, 80) # to draw circles match the radius painter.drawEllipse(QPoint(x, y), radius, radius) painter.end() app = QApplication(sys.argv) dp = DrawPoints() dp.show() app.exec_()
Last edited by Ene Uran; May 12th, 2009 at 2:32 pm.
drink her pretty
An example how to use the QPainter to create a wallpaper background:
python Syntax (Toggle Plain Text)
# a simple window using PyQT # using a canvas with a texture/wallpaper background import sys # pray for minimal namespace conflicts 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, 350, 300) self.setWindowTitle("Creating a Canvas Wallpaper") def paintEvent(self, event): """create a painting canvas""" painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) # use the brush for a texture/wallpaper background # supply a background image file you have (add needed path) painter.setBrush(QBrush(QPixmap("BG_GoldSwirl.gif"))) painter.drawRect(event.rect()) # optionally write something in the wallpaper # (check the fonts available on your computer) painter.setFont(QFont('Freestyle Script', 48)) painter.drawText(50, 160, "Hello World!") painter.end() app = QApplication(sys.argv) form = MyForm() form.show() app.exec_()
drink her pretty
![]() |
Similar Threads
- Starting wxPython (GUI code) (Python)
- Starting Python (Python)
- Starting with GUI programming? (Python)
- python script help (Python)
- Python GUI Problem (Python)
- C Software Programming.. (C++)
- Frequently Used Python Commands (Python)
- starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Python - Using a text file to feed into a python dictionary
- Next Thread: pygame problem
| Thread Tools | Search this Thread |
alarm ansi app assignment avogadro backend beginner binary bluetooth character cipher cmd customdialog cx-freeze data decimals dictionary directory dynamic error exe file float format function generator getvalue gnu graphics halp heads homework http ideas import input ip itunes java keycontrol leftmouse line linux list lists loop maintain maze millimeter module mouse number numbers output parsing path pointer prime programming progressbar push py2exe pygame python queue random recursion schedule screensaverloopinactive script slicenotation sqlite ssh statistics string strings sudokusolver sum text thread threading time tlapse tuple tutorial ubuntu unicode url urllib urllib2 variable variables ventrilo vigenere web webservice wikipedia write wxpython xlib






