| | |
Python GUI Programming
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
Look at PyQT's progress bar widget and simple timer to drive it:
python Syntax (Toggle Plain Text)
# pqt_progressbar1.py # explore PyQT's progress bar and simple timer widgets # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyFrame(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('QProgressBar') self.pbar = QProgressBar(self) self.pbar.setGeometry(30, 40, 200, 25) self.button = QPushButton('Start', self) self.button.setFocusPolicy(Qt.NoFocus) # absolute positioning self.button.move(40, 80) self.connect(self.button, SIGNAL('clicked()'), self.onStart) # QBasicTimer is simplified timer # use QTimer for more options and control self.timer = QBasicTimer() self.step = 0; def timerEvent(self, event): """preset method for timer widget""" if self.step >= 100: self.timer.stop() return self.step += 1 self.pbar.setValue(self.step) def onStart(self): """toggle button action and label""" if self.timer.isActive(): self.timer.stop() self.button.setText('Start') else: # timer interval of 100 milliseconds self.timer.start(100, self) self.button.setText('Stop') app = QApplication(sys.argv) frame = MyFrame() frame.show() app.exec_()
Should you find Irony, you can keep her!
Put PyQT widgets on a color background using canvas:
python Syntax (Toggle Plain Text)
# pqt_CanvasBackGround1.py # use PyQT's paintEvent to create full frame canvas # widgets will use the canvas as background # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyFrame(QWidget): def __init__(self): QWidget.__init__(self) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 350, 200) self.setWindowTitle("paintEvent canvas as background") # specify the canvas background color (r, g, b) self.plum = QColor(221, 160, 221) # create some regular widgets # that will use the canvas as background btn_red = QPushButton("Red") btn_green = QPushButton("Green") btn_blue = QPushButton("Blue") # the label acts transparent, buttons do not label = QLabel(" 1 \n 2 \n 3 \n 4 \n 5 \n 6 \n") # use grid layout for the widgets grid = QGridLayout() # addWidget(widget, row, column, rowSpan=1, columnSpan=1) grid.addWidget(btn_red, 0, 0, 1, 1) grid.addWidget(btn_green, 0, 1, 1, 1) grid.addWidget(btn_blue, 1, 0, 1, 1) grid.addWidget(label, 2, 0, 1, 1) self.setLayout(grid) def paintEvent(self, event): """auto-create the painting canvas""" painter = QPainter() painter.begin(self) # use brush for rectangle background painter.setBrush(QBrush(self.plum)) # set recangle to full frame size painter.drawRect(event.rect()) painter.end() app = QApplication(sys.argv) frame = MyFrame() frame.show() app.exec_()
Should you find Irony, you can keep her!
I got inspired by Henri's nice PyQT studies, so here is my small contribution, an "almost IDE" ...
python Syntax (Toggle Plain Text)
# pqt_RunPyFile2.pyw # run a given Python script file with a given version of Python # show the script and the result # use with Python3 or change line 82 and 83 # tested with Python31 and PyQT45 by vegaseat 05aug2009 import subprocess import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyWindow(QWidget): def __init__(self, python_path, initial_dir, *args): QWidget.__init__(self, *args) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 200, 640, 400) s = "Run a Python script file with %s" % python_path self.setWindowTitle(s) self.python_path = python_path self.initial_dir = initial_dir self.show_fname = QLineEdit() self.show_fname.setToolTip("press enter key") self.show_script = QTextEdit() self.show_result = QTextEdit() # use a vertical boc layout layout = QVBoxLayout(self) layout.addWidget(self.show_fname) layout.addWidget(self.show_script) layout.addWidget(self.show_result) self.setLayout(layout) self.file_dialog() self.load_script() # press return key in show_fname to start run_command() # allows you to add commandline args self.connect(self.show_fname, SIGNAL("returnPressed(void)"), self.run_command) def run_command(self): """use subprocess.Popen to run the command line""" py_file = str(self.show_fname.text()) self.setWindowTitle(py_file) py_exe = self.python_path option = "-u" py_script = py_file p = subprocess.Popen([py_exe, option, py_script], bufsize=2048, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=False) # write additional args to the external program #p.stdin.write("args") # allow external program to work p.wait() result_str = p.stdout.read() # the result is a bytearray in Python3 if type(result_str) != str: # decode <class 'bytes'> to string result_str = result_str.decode("utf8") s = "my result -->\n%s" % result_str self.show_result.setText(s) def file_dialog(self): """get the Python script file's mname""" #getOpenFileName (parent, caption, dir, filter, # selectedFilter, options) self.filename = QFileDialog.getOpenFileName(self, 'Open file', self.initial_dir, "Python files (*.py *.pyw)") self.show_fname.setText(self.filename) def load_script(self): # PyQT needs this elaborate process # to deal with loading text ... try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec("UTF-8") self.show_script.setPlainText(stream.readAll()) except IOError as e: # Python3 #except IOError, e: # Python2 QMessageBox.warning(self, "Load Error", "Failed to load %s: %s" % (self.filename, e)) finally: if fh is not None: fh.close() # modify for correct path and Operating System syntax python_path = "D:/Python31/Python.exe" initial_dir = "./" app = QApplication(sys.argv) win = MyWindow(python_path, initial_dir) win.show() sys.exit(app.exec_())
May 'the Google' be with you!
PyGame isn't the only toolkit you can use for animation. If you use Python 3.1 and still wait for PyGame to be available, you can use Tinter for some simple animations:
python Syntax (Toggle Plain Text)
# Tk_CanvasMove1.py # explore Tkinter animation via canvas.move() # Henri import time try: # for Python2 import Tkinter as tk except ImportError: # for Python3 import tkinter as tk root = tk.Tk() root.title("canvas.move() test") canvas = tk.Canvas(root, width=400, height=380) canvas.pack() # canvas.create_rectangle(x0, y0, x1, y1, option, ... ) # x0, y0, x1, y1 are corner coordinates of ulc to lrc diagonal rc1 = canvas.create_rectangle(20, 260, 120, 360, outline='white', fill='blue') rc2 = canvas.create_rectangle(20, 10, 120, 110, outline='white', fill='red') # initial delay to view setting canvas.update() time.sleep(0.7) for x in range(50): y = x = 5 time.sleep(0.025) # canvas.move(obj, xAmount, yAmount) # objects are rectangles rc1 and rc2 canvas.move(rc1, x, -y) canvas.move(rc2, x, y) canvas.update() time.sleep(0.7) # reverse move for x in range(50, 0, -1): y = x = -5 time.sleep(0.025) # canvas.move(obj, xAmount, yAmount) # objects are rectangles rc1 and rc2 canvas.move(rc1, x, -y) canvas.move(rc2, x, y) canvas.update() root.mainloop()
Should you find Irony, you can keep her!
In the previous example I meant 'Tkinter' rather than 'Tinter'. This however is PyQT example looking at the tooltip widget and some colored text:
python Syntax (Toggle Plain Text)
# pqt_tooltip1.py # exploring PyQT's tooltip and color text (html) # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class Tooltip(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Tooltip') btn_hello = QPushButton("Push Button") btn_hello.setToolTip('Press <b>me</b> for the greeting') self.connect(btn_hello, SIGNAL("clicked()"), self.on_click) self.label = QLabel() grid = QGridLayout() grid.addWidget(btn_hello, 0, 0, 1, 1) grid.addWidget(self.label, 1, 0, 1, 3) self.setLayout(grid) def on_click(self): s = "<font size=6 color='red'>Hello stranger!</font>" self.label.setText(s) app = QApplication(sys.argv) tooltip = Tooltip() tooltip.show() app.exec_()
Should you find Irony, you can keep her!
Retrieve the text from Tkinter Text widget line by line:
python Syntax (Toggle Plain Text)
# explore the Tkinter Text() widget # getting text 'line by line' from the widget # use ctrl+c to copy, ctrl+x to cut selected text, # ctrl+v to paste, and ctrl+/ to select all # Henri try: # for Python2 import Tkinter as tk except ImportError: # for Python3 import tkinter as tk def get_text(event): """get text widget contents of given line n (firstline=1)""" # retrieve the line number from button text n = int(event.widget.cget("text")) # set up start and end of the line start = "%d.0" % n end = "%d.end" % n # get the line text s = text.get(start, end) # show it in the label label['text'] = s # test data mw = """\ Na Sodium 22.98977 Mg Magnesium 24.305 Al Aluminum 26.98154 Si Silicon 28.0855 P Phosphorus 30.97376 S Sulfur 32.066 Cl Chlorine 35.4527 Ar Argon 39.948""" root = tk.Tk() root.title('get text line by line') # text field, width=width chars, height=lines text text = tk.Text(root, width=30, height=8, bg='yellow') text.insert('insert', mw) text.pack(pady=5) # create buttons to call each line by number for n, data in enumerate(mw.split('\n')): # first line in text is 1 s = str(n+1) btn = tk.Button(root, text=s) btn.bind("<Button-1>", get_text) btn.pack(side='left', pady=5, padx=2) # width/height in char size label = tk.Label(root, text="", width=30, height=2) label.pack(side='top', pady=5) root.mainloop()
Should you find Irony, you can keep her!
Here is an example of a scrolled Tkinter canvas to display a series of drawn objects or pictures:
python Syntax (Toggle Plain Text)
# example of a Tkinter scrolled canvas class # snee try: # for Python2 import Tkinter as tk except ImportError: # for Python3 import tkinter as tk class ScrolledCanvas(tk.Frame): def __init__(self, parent=None, color='brown'): tk.Frame.__init__(self, parent) self.pack(expand='yes', fill='both') self.parent = parent canvas = tk.Canvas(self, bg=color, relief='sunken') #canvas.config(width=300, height=200) canvas.config(scrollregion=(0, 0, 300, 1000)) canvas.config(highlightthickness=0) sbar = tk.Scrollbar(self) # vertical scrollbar sbar.config(command=canvas.yview) canvas.config(yscrollcommand=sbar.set) sbar.pack(side='right', fill='y') canvas.pack(side='left', expand='yes', fill='both') # put in some text for testing ... for k in range(10): s = 'now calling #' + str(k) canvas.create_text(150, 50+(k*100), text=s, fill='beige') # for testing canvas (x, y) canvas.bind('<Double-1>', self.onDoubleClick) self.canvas = canvas def onDoubleClick(self, event): """show location (x, y) of double click on canvas""" #print( event.x, event.y ) x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) s = "x = %s y = %s" % (x, y) self.parent.title(s) if __name__ == '__main__': root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (350, 250, 100, 80)) root.title('testing the scrolled canvas') ScrolledCanvas(root).mainloop()
No one died when Clinton lied.
The Tkinter version that comes with the Python 3.1 installation includes expansion module ttk. This module includes a couple of widgets missing from Tkinter, like a tabbed notebook. As usual, actual examples are totally missing from the Python manual, so I give you at least a hint of its use ...
And here is the combobox, a combination of drop down listbox and entrybox ...
python Syntax (Toggle Plain Text)
# ttk_notebook1.py # exploring the Tkinter expansion module ttk notebook # tested with Python 3.1 and Tkinter 8.5 by vegaseat import tkinter as tk import tkinter.ttk as ttk root = tk.Tk() # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (300, 200, 100, 50)) root.title('test the ttk.Notebook') nb = ttk.Notebook(root) nb.pack(fill='both', expand='yes') # create a child wdget for each page f1 = tk.Frame(bg='red') f2 = tk.Frame(bg='blue') f3 = tk.Frame(bg='green') # create the pages nb.add(f1, text='page1') nb.add(f2, text='page2') nb.add(f3, text='page3') # put a button widget on child f1 btn1 = tk.Button(f1, text='button1') btn1.pack(side='left', anchor='nw', padx=3, pady=5) root.mainloop()
python Syntax (Toggle Plain Text)
# ttk_combobox2.py # exploring the Tkinter expansion module ttk combobox # tested with Python 3.1 and Tkinter 8.5 by vegaseat import tkinter as tk import tkinter.ttk as ttk def action(event): """ a combo box item has been selected, do some action """ label['bg'] = combo.get() root = tk.Tk() # create a label label = tk.Label(text='select a color', bg='white') # create the combo box combo = ttk.Combobox() combo.bind('<<ComboboxSelected>>', action) colors = ['red', 'green', 'magenta', 'yellow'] # load the combo box with the colors list combo['values'] = colors # set the initial color combo.set('yellow') label['bg'] = combo.get() # pack the widgets vertically in this order label.pack(fill='both', expand='yes') combo.pack() root.mainloop()
Last edited by vegaseat; Aug 14th, 2009 at 8:33 pm. Reason: combobox
May 'the Google' be with you!
Here is a basic template of a window, 2 buttons and a label using the pygtk toolkit:
python Syntax (Toggle Plain Text)
# a very basic pygtk window template # with two buttons and one label # snee import pygtk pygtk.require('2.0') import gtk class MyWindow(object): def __init__(self): # type=gtk.WINDOW_TOPLEVEL is default self.window = gtk.Window() # pygtk needs this # attach destroy signal to terminate application properly self.window.connect("destroy", lambda w: gtk.main_quit()) # title bar caption self.window.set_title("gtk.Window template") # put upper left corner on display coordinates (x, y) self.window.move(100, 80) # resize(width, height) self.window.resize(350, 150) # create 2 button widgets and a label widget button1 = gtk.Button("Button 1") # connect mouse click to a callback button1.connect("clicked", self.callback, "Tom") button2 = gtk.Button("Button 2") # connect mouse click to a callback button2.connect("clicked", self.callback, "Frank") self.label = gtk.Label("Hello!") # create a vertical box to pack the widgets into box_v = gtk.VBox(False, 0) self.window.add(box_v) # now pack the widgets into the box (top to bottom order) box_v.pack_start(button1, False, False, 0) box_v.pack_start(button2, False, False, 0) box_v.pack_start(self.label, True, True, 0) # now show all the widgets including the window button1.show() button2.show() self.label.show() box_v.show() self.window.show() def callback(self, widget, data=None): s = "You clicked %s's button" % data self.window.set_title(s) if data == "Tom": self.label.set_text("Major Tom") else: self.label.set_text("Major Frank Burns") MyWindow() gtk.main()
No one died when Clinton lied.
If you have young children at home, or are yourself a young child at heart, there is a delightful Python module called frog, that does turtle like drawings and more:
Just a little more for the fun of it:
python Syntax (Toggle Plain Text)
# frog is a somewhat advanced turtle graphics module # get frog-1.0.1.zip from: # http://www.zahlenfreund.de/python/frog.html # see also: # http://pypi.python.org/pypi/frog/1.0.0 # unzip and copy frog.py into the Python lib folder # or use it in the working folder # works with Python2 and Python3 import frog # pond forms the canvas pond = frog.Pool() pond.title = "Watch the frog move and draw" pond.bgcolor = "lightblue" # kermit forms the drawing pen kermit = frog.Frog(pond) kermit.shape = "frog" kermit.bodycolor = "green" # kermit draws a square # starts at the center of the pond for n in range(4): kermit.move(100) kermit.turn(90) # turn kermit in the other direction kermit.turn(180) for n in range(4): kermit.move(100) kermit.turn(90) pond.ready()
python Syntax (Toggle Plain Text)
# get frog-1.0.1.zip from: # http://www.zahlenfreund.de/python/frog.html # unzip and copy frog.py into the Python lib folder # or use it in the working folder # works with Python2 and Python3 import frog canvas = frog.Pool() canvas.setbgcolor('green') # use the default triangle shape pen = frog.Frog(canvas) pen.color = "red" # pen normally starts in the canvas center # make it jump (no drawing) left and then down pen.jump(-50) pen.turn(90) pen.jump(-25) pen.turn(270) # the pen draws a number of 'pentagon shapes' # starts at the center and forms a star for n in range(9): pen.move(100) pen.turn(80) canvas.ready()
No one died when Clinton lied.
![]() |
Similar Threads
- Starting Python (Python)
- Starting wxPython (GUI code) (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: Help with pythagorean theory solver
- Next Thread: staticmethod
| Thread Tools | Search this Thread |
6 accessdenied advice aliased apax applicaions backend beginner c++ calculator calling client code color coordinates corners curves cx-freeze database dictionary digital dragging dynamic edit editing editor error event examples excel file filename forms function google gui halp html iframe images input ip java keyboard launcher line linux list lists loop microphone movingimageswithpygame mysqldb opensource output path problem programming projects py2exe pygame pygtk python random redirect ruby rubyconf samples script shebang skinning slicenotation smtp software source sqlite ssh stop string sudokusolver table text textfields threading tkinter tlapse toolbar tutorial ubuntu unicode urllib urllib2 variable voip windows wordgame write wxpython xui xwnidow







