| | |
Python GUI Programming
![]() | View First Unread |
A small Python/PyQT4 utility program to find out what kind of fonts your computer has:
Save the code as pqt_FontLister.pyw
python Syntax (Toggle Plain Text)
# bring up a font dialog with PyQT4 # show the selected font using a sample text import sys # hopefully no namespace conflicts from PyQt4.QtCore import * from PyQt4.QtGui import * class FontDialog(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setGeometry(10, 100, 250, 110) self.setWindowTitle('QFontDialog') hbox = QVBoxLayout() button = QPushButton('Font Dialog') self.connect(button, SIGNAL('clicked()'), self.showDialog) # the label autosizes to the text text = "The quick brown fox jumps over the lazy dog" self.label = QLabel(text) self.label.move(130, 20) self.edit = QTextEdit() hbox.addWidget(button) hbox.addWidget(self.label) hbox.addWidget(self.edit) self.setLayout(hbox) def showDialog(self): font, ok = QFontDialog.getFont() if ok: # display the label's text in the selected font self.label.setFont(font) # display the font name in the edit box for copying self.edit.append(QFontInfo(font).family()) app = QApplication(sys.argv) fd = FontDialog() fd.show() app.exec_()
Last edited by Ene Uran; May 13th, 2009 at 1:06 am.
drink her pretty
Tkinter has the reputation to look kind of homely on Windows computers. Actually, on my Ubuntu/Linux computer it doesn't look bad at all. Here is a typical listbox example using the Tkinter GUI toolkit that comes with just about every Python installation. Yes, if you use the new Python3, it comes with Tkinter too. Just remember that Tkinter is now a package and you have to import tkinter rather than Tkinter:
Again, the first line in my code is for Linux to find the Python interpreter. I really like the Firefox web browser and its built in automatic spell checker.
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # create a scrollable listbox using Tkinter # load the listbox with tasty cheese data # and select your favorite cheese with the mouse # with Python3 use import tkinter as tk import Tkinter as tk def get_list(event): """ function to read the listbox selection and put the result in a label widget """ # get selected line index index = listbox.curselection()[0] # get the line's text seltext = listbox.get(index) # put the selected text in the label label['text'] = seltext root = tk.Tk() root.title("Cheeses") # use width x height + x_offset + y_offset (no spaces!) root.geometry("180x300+30+50") # create a label (width in characters) s = "Click on a cheese" label = tk.Label(root, text= s, width=15) label.grid(row=0, column=0) # create a listbox (height in characters/lines) # give it a nice yellow background (bg) color listbox = tk.Listbox(root, height=15, bg='yellow') listbox.grid(row=1, column=0) # the Tkinter listbox does not automatically scroll, you need # to create a vertical scrollbar to the right of the listbox yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL) yscroll.grid(row=1, column=1, sticky='n'+'s') listbox.configure(yscrollcommand=yscroll.set) cheese_list = [ 'Feta', 'Limburger', 'Camembert', 'Roquefort', 'Edam', 'Romadur', 'Liptauer', 'Dubliner', 'Gouda', 'Gorgonzola', 'Jarlsberg', 'Golka', 'Garrotxa', 'Swiss', 'Quesillo', 'Emmentaler', 'Appenzeller', 'Raclette', 'Asiago', 'Zuvi', 'Ricotta', 'Mozzarella', 'Munster', 'Parmesan'] # load the listbox for item in cheese_list: listbox.insert('end', item) # use left mouse click on a list item to display selection listbox.bind('<ButtonRelease-1>', get_list) root.mainloop()
Last edited by sneekula; May 13th, 2009 at 5:19 pm.
No one died when Clinton lied.
The nice thing about using a GUI toolkit is that you have a large number of widgets available to supply the data input. Here is a Tkinter Temperature Converter example using radio buttons to select the type of conversion and a scale (slider) to set the temperature. Notice that the result is updated as changes to the inputs are made:
Once more, the first line in my code is for Linux to find the Python interpreter. If you have Windows, Windows will ignore this line or you can. Also, if you use the newer Python3 version, use import tkinter as tk.
python Syntax (Toggle Plain Text)
#!/usr/bin/env python # use Tkinter's scale/slider and radiobutton widgets # for input data to convert temperature values import Tkinter as tk def on_click(): """radio button clicked, change results too""" on_move() def on_move(value=0): """use slider position to calculate and display result""" # radio button1 is set convert C to F if rb_v.get() == id_rb1: c = scale.get() f = c*9/5.0 + 32 result = "%s celsius --> %s Fahrenheit" % (c, f) # radio button2 is set convert F to C else: f = scale.get() c = (f - 32)*5/9.0 result = "%s Fahrenheit --> %s Celsius" % (f, c) label['text'] = result root = tk.Tk() root.title('Temperature Converter') # use width x height + x_offset + y_offset (no spaces!) root.geometry("620x110+30+50") # used by the radio button_id rb_v = tk.IntVar() # the radio buttons allow selection of Celsius or Fahrenheit id_rb1 = 101 rb1 = tk.Radiobutton(root, text='Celsius to Fahrenheit', value=id_rb1, variable=rb_v, command=on_click) id_rb2 = 102 rb2 = tk.Radiobutton(root, text='Fahrenheit to Celsius', value=id_rb2, variable=rb_v, command=on_click) # start with rb1 selected rb_v.set(id_rb1) # the scale (or slider) selects the temperature # from -50 to +300 # (from_ is used because from is a reserved word in Python) scale = tk.Scale(root, label="select temperature", from_=-50, to=300, tickinterval=0, resolution=1, length=600, showvalue='yes', orient='horizontal', command=on_move) # set the starting position of the scale scale.set(50) # show the result in a label label = tk.Label(root, text='---', bg='yellow') # place the widgets in a grid rb1.grid(row=0, column=0) rb2.grid(row=0, column=1) scale.grid(row=1, columnspan=2) label.grid(row=2, columnspan=2, pady=5) root.mainloop()
Last edited by vegaseat; May 15th, 2009 at 9:31 pm. Reason: corrected scale comment
No one died when Clinton lied.
Tkinter has some nice pop-up dialogs that can also be used for regular console programs. Here is an example to use if you want to get a filename from a pop-up window. It works with Python2x or Python3x, just read the comments:
python Syntax (Toggle Plain Text)
# use Tkinter's file dialog window to get # a file name with full path, you can also use # this to get filenames for a console program # askopenfilename() gives one selected filename # with Python25 use ... #import Tkinter as tk #from tkFileDialog import askopenfilename # with Python30 use ... import tkinter as tk from tkinter.filedialog import askopenfilename root = tk.Tk() # show askopenfilename dialog without the Tkinter window root.withdraw() # default is all file types file_name = askopenfilename() print(file_name)
drink her pretty
This code sample shows you how to select and display multiple lines from a Tkinter Listbox ...
Left mouse click with and without pressing the SHIFT or CTRL key to see how the multiple selection works.
python Syntax (Toggle Plain Text)
# a simple Tkinter Listbox example # press the shift or ctrl key to select multiple items # source: snee import Tkinter as tk def get_list(): """ function to read the listbox selection(s) (mutliple lines can be selected) and put the result(s) in a label """ # tuple of line index(es) sel = listbox.curselection() # get the text, might be multi-line seltext = '\n'.join([listbox.get(x) for x in sel]) label_text.set(seltext) root = tk.Tk() # used for label text label_text = tk.StringVar(root) # extended mode allows CTRL/SHIFT mouse selections listbox = tk.Listbox(root, selectmode=tk.EXTENDED) listbox.pack() # click the button to show the selection(s) button = tk.Button(root, text="Get Selection(s)", command=get_list) button.pack() # used to display selection(s) label = tk.Label(root, textvariable=label_text) label.pack() # load some datalines into the listbox items = ["one", "two", "three", "four", "five", "six"] for item in items: listbox.insert(tk.END, item) # highlight/preselect line 3 of listbox (starts with zero) # lb.selection_set(first, last=None) can preselect more than 1 line listbox.selection_set(3) root.mainloop()
May 'the Google' be with you!
I modernized an old snippet of mine ...
python Syntax (Toggle Plain Text)
# Tkinter GUI program with 2 data entry, labels and a button # a general template to input 2 numbers and calculate something # here the resistance of 2 resistors in parallel # for Python3 use: import tkinter as tk # vegaseat import Tkinter as tk def calculate(): """ calculate the resistance of 2 resistors in parallel """ try: r1 = float(enter1.get()) r2 = float(enter2.get()) if r1 + r2 > 0: rp = (r1 * r2) / (r1 + r2) result = "Result = %0.2f" % rp label3.config(text=result) else: label3.config(text='Division by zero error') except ValueError: label3.config(text='Need numeric values') def setfocus2(event): enter2.focus_set() # create root window root = tk.Tk() root.title("Parallel resistance ...") # create all the components label1 = tk.Label(root, text=' Enter value of resistor1:') enter1 = tk.Entry(root, bg='yellow') label2 = tk.Label(root, text=' Enter value of resistor2:') enter2 = tk.Entry(root, bg='yellow') btn1 = tk.Button(root, text=' Calculate ', command=calculate) label3 = tk.Label(root, text='') # use a grid for component layout label1.grid(row=0, column=0) enter1.grid(row=0, column=1, padx=5, pady=5) label2.grid(row=1, column=0) enter2.grid(row=1, column=1) btn1.grid(row=2, column=0, pady=5) label3.grid(row=2, column=1) # start cursor in enter1 enter1.focus_set() # return key in enter1 sets focus to enter2 enter1.bind("<Return>", func=setfocus2) # start event loop and program root.mainloop()
Last edited by vegaseat; Jun 10th, 2009 at 10:20 pm. Reason: picture
May 'the Google' be with you!
Those little animated gif image files are fun. Here is an example of using PyQt's QMovie() widget to play them ...
python Syntax (Toggle Plain Text)
# use PyQt's QMovie() widget to play an animated gif # tested with PyQt4.4 and Python 2.5 # also tetsed with PyQt4.5 and Python 3.0 # vegaseat import sys # expect minimal namespace conflicts from PyQt4.QtCore import * from PyQt4.QtGui import * class MoviePlayer(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(200, 200, 400, 300) self.setWindowTitle("QMovie to show animated gif") # set up the movie screen on a label self.movie_screen = QLabel() # expand and center the label self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) # use an animated gif file you have in the working folder # or give the full file path movie = QMovie("AG_Dog.gif", QByteArray(), self) movie.setCacheMode(QMovie.CacheAll) movie.setSpeed(100) self.movie_screen.setMovie(movie) movie.start() app = QApplication(sys.argv) player = MoviePlayer() player.show() sys.exit(app.exec_())
May 'the Google' be with you!
Draw a simple bar chart with PyQT:
python Syntax (Toggle Plain Text)
# use PyQT to draw a simple vertical bar chart # tested with PyQT4.5 and Python3.0 # ene import sys # simplified import, hopefully no namespace conflicts from PyQt4.QtCore import * from PyQt4.QtGui import * class BarChart(QWidget): def __init__(self, data, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 360, 320) self.setWindowTitle('A Simple Bar Chart') self.data = data def paintEvent(self, event): painter = QPainter() painter.begin(self) # set color and width of line drawing pen painter.setPen(QPen(Qt.black, 2)) # drawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2) # draw the baseline painter.drawLine(20, 280, 340, 280) # set up color and width of the bars width = 20 painter.setPen(QPen(Qt.red, width)) delta = width + 5 x = 30 for y in self.data: # correct for width y1 = 280 - width/2 y2 = y1 - y + width/2 # draw each bar painter.drawLine(x, y1, x, y2) # add values to the top of each bar s = str(y) painter.drawText(x-8, y2-15, s) x += delta painter.end() # data to be graphed data = [30, 45, 80, 150, 220, 180, 110, 75, 50, 35, 20, 10] app = QApplication(sys.argv) bc = BarChart(data) bc.show() app.exec_()
drink her pretty
PyQT has an interesting widget called a dial (circular slider). Here is a simple applcation:
Sorry, I am having real problems with my HP notebook, the keyboard is of very poor quality and misses keystrokes a lot!
python Syntax (Toggle Plain Text)
# use a PyQT QDial knob to select a temperature # show Celsius and corresponding Fahrenheit values # as the knob is rotated # tested with PyQT4.5 and Python3.0 # ene import sys # has minimal namespace conflicts 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(150, 150, 328, 440) self.setWindowTitle('Convert Temperature') self.dial = QDial(self) self.dial.setGeometry(QRect(10, 20, 311, 351)) self.dial.setMinimum(-50) self.dial.setMaximum(310) self.dial.setPageStep(10) # initial dial pointer position dial_pos = 50 self.dial.setSliderPosition(dial_pos) self.dial.setWrapping(True) self.dial.setNotchTarget(3.6) self.dial.setNotchesVisible(True) self.label_c = QLabel(self) self.label_c.setGeometry(QRect(30, 390, 121, 31)) font = QFont() font.setPointSize(11) self.label_c.setFont(font) self.label_c.setAlignment(Qt.AlignCenter) self.label_f = QLabel(self) self.label_f.setGeometry(QRect(170, 390, 131, 31)) font = QFont() font.setPointSize(11) self.label_f.setFont(font) self.label_f.setAlignment(Qt.AlignCenter) # start up self.show_temps() # update show_temps() self.connect(self.dial, SIGNAL("sliderMoved(int)"), self.show_temps) def show_temps(self): """ get the C value from the dial label calculate F value and show """ c = float(self.dial.value()) s_c = "%0.1f Celsius" % c self.label_c.setText(s_c) f = c*9/5.0 + 32 s_f = "%0.1f Fahrenheit" % f self.label_f.setText(s_f) app = QApplication(sys.argv) frame = MyFrame() frame.show() sys.exit(app.exec_())
Last edited by vegaseat; Jun 18th, 2009 at 7:33 pm. Reason: Bug removed at Ene's request
drink her pretty
An example how to use an image as a background. In order to make added text transparent, use the Tkinter canvas:
python Syntax (Toggle Plain Text)
# use a Tkinter canvas for a background image # add transparent text and other widgets # with Python3 use import tkinter as tk # snee import Tkinter as tk root = tk.Tk() root.title('background image') # pick a .gif image file you have in the working directory bg_image = tk.PhotoImage(file="Flowers.gif") w = bg_image.width() h = bg_image.height() # size the window so the image will fill it root.geometry("%dx%d+0+0" % (w, h)) cv = tk.Canvas(width=w, height=h) cv.pack(side='top', fill='both', expand='yes') cv.create_image(0, 0, image=bg_image, anchor='nw') # add canvas text at coordinates x=15, y=30 # anchor='nw' implies upper left corner coordinates cv.create_text(15, 30, text="Python Greetings", fill="red", anchor='nw') # now some button widgets btn1 = tk.Button(cv, text="Click") btn1.pack(side='left', padx=10, pady=5, anchor='sw') btn2 = tk.Button(cv, text="Quit") btn2.pack(side='left', padx=10, pady=5, anchor='sw') root.mainloop()
No one died when Clinton lied.
![]() |
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: Displaying eyes
- Next Thread: Changing color of Text area characters using Tk
| 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 scrolledtext slicenotation sqlite ssh statistics string strings sudokusolver sum text thread threading time tlapse tuple tutorial ubuntu unicode urllib urllib2 variable variables ventrilo vigenere web webservice wikipedia write wxpython xlib







