Python GUI Programming

Reply

Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Python GUI Programming

 
1
  #11
May 13th, 2009
A small Python/PyQT4 utility program to find out what kind of fonts your computer has:
  1. # bring up a font dialog with PyQT4
  2. # show the selected font using a sample text
  3.  
  4. import sys
  5. # hopefully no namespace conflicts
  6. from PyQt4.QtCore import *
  7. from PyQt4.QtGui import *
  8.  
  9. class FontDialog(QWidget):
  10. def __init__(self, parent=None):
  11. QWidget.__init__(self, parent)
  12. self.setGeometry(10, 100, 250, 110)
  13. self.setWindowTitle('QFontDialog')
  14.  
  15. hbox = QVBoxLayout()
  16.  
  17. button = QPushButton('Font Dialog')
  18. self.connect(button, SIGNAL('clicked()'), self.showDialog)
  19.  
  20. # the label autosizes to the text
  21. text = "The quick brown fox jumps over the lazy dog"
  22. self.label = QLabel(text)
  23. self.label.move(130, 20)
  24.  
  25. self.edit = QTextEdit()
  26.  
  27. hbox.addWidget(button)
  28. hbox.addWidget(self.label)
  29. hbox.addWidget(self.edit)
  30. self.setLayout(hbox)
  31.  
  32. def showDialog(self):
  33. font, ok = QFontDialog.getFont()
  34. if ok:
  35. # display the label's text in the selected font
  36. self.label.setFont(font)
  37. # display the font name in the edit box for copying
  38. self.edit.append(QFontInfo(font).family())
  39.  
  40.  
  41. app = QApplication(sys.argv)
  42. fd = FontDialog()
  43. fd.show()
  44. app.exec_()
Save the code as pqt_FontLister.pyw
Last edited by Ene Uran; May 13th, 2009 at 1:06 am.
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 174
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Python GUI Programming

 
1
  #12
May 13th, 2009
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:
  1. #!/usr/bin/env python
  2.  
  3. # create a scrollable listbox using Tkinter
  4. # load the listbox with tasty cheese data
  5. # and select your favorite cheese with the mouse
  6. # with Python3 use import tkinter as tk
  7.  
  8. import Tkinter as tk
  9.  
  10. def get_list(event):
  11. """
  12. function to read the listbox selection
  13. and put the result in a label widget
  14. """
  15. # get selected line index
  16. index = listbox.curselection()[0]
  17. # get the line's text
  18. seltext = listbox.get(index)
  19. # put the selected text in the label
  20. label['text'] = seltext
  21.  
  22. root = tk.Tk()
  23. root.title("Cheeses")
  24. # use width x height + x_offset + y_offset (no spaces!)
  25. root.geometry("180x300+30+50")
  26.  
  27. # create a label (width in characters)
  28. s = "Click on a cheese"
  29. label = tk.Label(root, text= s, width=15)
  30. label.grid(row=0, column=0)
  31.  
  32. # create a listbox (height in characters/lines)
  33. # give it a nice yellow background (bg) color
  34. listbox = tk.Listbox(root, height=15, bg='yellow')
  35. listbox.grid(row=1, column=0)
  36.  
  37. # the Tkinter listbox does not automatically scroll, you need
  38. # to create a vertical scrollbar to the right of the listbox
  39. yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL)
  40. yscroll.grid(row=1, column=1, sticky='n'+'s')
  41. listbox.configure(yscrollcommand=yscroll.set)
  42.  
  43. cheese_list = [
  44. 'Feta', 'Limburger', 'Camembert', 'Roquefort', 'Edam',
  45. 'Romadur', 'Liptauer', 'Dubliner', 'Gouda', 'Gorgonzola',
  46. 'Jarlsberg', 'Golka', 'Garrotxa', 'Swiss', 'Quesillo',
  47. 'Emmentaler', 'Appenzeller', 'Raclette', 'Asiago', 'Zuvi',
  48. 'Ricotta', 'Mozzarella', 'Munster', 'Parmesan']
  49.  
  50. # load the listbox
  51. for item in cheese_list:
  52. listbox.insert('end', item)
  53.  
  54. # use left mouse click on a list item to display selection
  55. listbox.bind('<ButtonRelease-1>', get_list)
  56.  
  57. root.mainloop()
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.
Last edited by sneekula; May 13th, 2009 at 5:19 pm.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 174
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Python GUI Programming

 
1
  #13
May 15th, 2009
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:
  1. #!/usr/bin/env python
  2.  
  3. # use Tkinter's scale/slider and radiobutton widgets
  4. # for input data to convert temperature values
  5.  
  6. import Tkinter as tk
  7.  
  8. def on_click():
  9. """radio button clicked, change results too"""
  10. on_move()
  11.  
  12. def on_move(value=0):
  13. """use slider position to calculate and display result"""
  14. # radio button1 is set convert C to F
  15. if rb_v.get() == id_rb1:
  16. c = scale.get()
  17. f = c*9/5.0 + 32
  18. result = "%s celsius --> %s Fahrenheit" % (c, f)
  19. # radio button2 is set convert F to C
  20. else:
  21. f = scale.get()
  22. c = (f - 32)*5/9.0
  23. result = "%s Fahrenheit --> %s Celsius" % (f, c)
  24. label['text'] = result
  25.  
  26. root = tk.Tk()
  27. root.title('Temperature Converter')
  28. # use width x height + x_offset + y_offset (no spaces!)
  29. root.geometry("620x110+30+50")
  30.  
  31. # used by the radio button_id
  32. rb_v = tk.IntVar()
  33.  
  34. # the radio buttons allow selection of Celsius or Fahrenheit
  35. id_rb1 = 101
  36. rb1 = tk.Radiobutton(root, text='Celsius to Fahrenheit',
  37. value=id_rb1, variable=rb_v, command=on_click)
  38. id_rb2 = 102
  39. rb2 = tk.Radiobutton(root, text='Fahrenheit to Celsius',
  40. value=id_rb2, variable=rb_v, command=on_click)
  41. # start with rb1 selected
  42. rb_v.set(id_rb1)
  43.  
  44. # the scale (or slider) selects the temperature
  45. # from -50 to +300
  46. # (from_ is used because from is a reserved word in Python)
  47. scale = tk.Scale(root, label="select temperature",
  48. from_=-50, to=300, tickinterval=0, resolution=1, length=600,
  49. showvalue='yes', orient='horizontal', command=on_move)
  50. # set the starting position of the scale
  51. scale.set(50)
  52.  
  53. # show the result in a label
  54. label = tk.Label(root, text='---', bg='yellow')
  55.  
  56. # place the widgets in a grid
  57. rb1.grid(row=0, column=0)
  58. rb2.grid(row=0, column=1)
  59. scale.grid(row=1, columnspan=2)
  60. label.grid(row=2, columnspan=2, pady=5)
  61.  
  62. root.mainloop()
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.
Last edited by vegaseat; May 15th, 2009 at 9:31 pm. Reason: corrected scale comment
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Python GUI Programming

 
1
  #14
May 24th, 2009
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:
  1. # use Tkinter's file dialog window to get
  2. # a file name with full path, you can also use
  3. # this to get filenames for a console program
  4. # askopenfilename() gives one selected filename
  5.  
  6. # with Python25 use ...
  7. #import Tkinter as tk
  8. #from tkFileDialog import askopenfilename
  9.  
  10. # with Python30 use ...
  11. import tkinter as tk
  12. from tkinter.filedialog import askopenfilename
  13.  
  14. root = tk.Tk()
  15. # show askopenfilename dialog without the Tkinter window
  16. root.withdraw()
  17.  
  18. # default is all file types
  19. file_name = askopenfilename()
  20.  
  21. print(file_name)
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 870
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Python GUI Programming

 
0
  #15
Jun 8th, 2009
This code sample shows you how to select and display multiple lines from a Tkinter Listbox ...
  1. # a simple Tkinter Listbox example
  2. # press the shift or ctrl key to select multiple items
  3. # source: snee
  4.  
  5. import Tkinter as tk
  6.  
  7. def get_list():
  8. """
  9. function to read the listbox selection(s)
  10. (mutliple lines can be selected)
  11. and put the result(s) in a label
  12. """
  13. # tuple of line index(es)
  14. sel = listbox.curselection()
  15. # get the text, might be multi-line
  16. seltext = '\n'.join([listbox.get(x) for x in sel])
  17. label_text.set(seltext)
  18.  
  19. root = tk.Tk()
  20. # used for label text
  21. label_text = tk.StringVar(root)
  22.  
  23. # extended mode allows CTRL/SHIFT mouse selections
  24. listbox = tk.Listbox(root, selectmode=tk.EXTENDED)
  25. listbox.pack()
  26.  
  27. # click the button to show the selection(s)
  28. button = tk.Button(root, text="Get Selection(s)", command=get_list)
  29. button.pack()
  30.  
  31. # used to display selection(s)
  32. label = tk.Label(root, textvariable=label_text)
  33. label.pack()
  34.  
  35. # load some datalines into the listbox
  36. items = ["one", "two", "three", "four", "five", "six"]
  37. for item in items:
  38. listbox.insert(tk.END, item)
  39.  
  40. # highlight/preselect line 3 of listbox (starts with zero)
  41. # lb.selection_set(first, last=None) can preselect more than 1 line
  42. listbox.selection_set(3)
  43.  
  44. root.mainloop()
Left mouse click with and without pressing the SHIFT or CTRL key to see how the multiple selection works.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 870
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Python GUI Programming

 
0
  #16
Jun 10th, 2009
I modernized an old snippet of mine ...
  1. # Tkinter GUI program with 2 data entry, labels and a button
  2. # a general template to input 2 numbers and calculate something
  3. # here the resistance of 2 resistors in parallel
  4. # for Python3 use: import tkinter as tk
  5. # vegaseat
  6.  
  7. import Tkinter as tk
  8.  
  9. def calculate():
  10. """ calculate the resistance of 2 resistors in parallel """
  11. try:
  12. r1 = float(enter1.get())
  13. r2 = float(enter2.get())
  14. if r1 + r2 > 0:
  15. rp = (r1 * r2) / (r1 + r2)
  16. result = "Result = %0.2f" % rp
  17. label3.config(text=result)
  18. else:
  19. label3.config(text='Division by zero error')
  20. except ValueError:
  21. label3.config(text='Need numeric values')
  22.  
  23. def setfocus2(event):
  24. enter2.focus_set()
  25.  
  26.  
  27. # create root window
  28. root = tk.Tk()
  29. root.title("Parallel resistance ...")
  30.  
  31. # create all the components
  32. label1 = tk.Label(root, text=' Enter value of resistor1:')
  33. enter1 = tk.Entry(root, bg='yellow')
  34. label2 = tk.Label(root, text=' Enter value of resistor2:')
  35. enter2 = tk.Entry(root, bg='yellow')
  36. btn1 = tk.Button(root, text=' Calculate ', command=calculate)
  37. label3 = tk.Label(root, text='')
  38.  
  39. # use a grid for component layout
  40. label1.grid(row=0, column=0)
  41. enter1.grid(row=0, column=1, padx=5, pady=5)
  42. label2.grid(row=1, column=0)
  43. enter2.grid(row=1, column=1)
  44. btn1.grid(row=2, column=0, pady=5)
  45. label3.grid(row=2, column=1)
  46.  
  47. # start cursor in enter1
  48. enter1.focus_set()
  49.  
  50. # return key in enter1 sets focus to enter2
  51. enter1.bind("<Return>", func=setfocus2)
  52.  
  53. # start event loop and program
  54. root.mainloop()
Last edited by vegaseat; Jun 10th, 2009 at 10:20 pm. Reason: picture
Attached Thumbnails
Tk_ParResistor.jpg  
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 870
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Python GUI Programming

 
0
  #17
Jun 12th, 2009
Those little animated gif image files are fun. Here is an example of using PyQt's QMovie() widget to play them ...
  1. # use PyQt's QMovie() widget to play an animated gif
  2. # tested with PyQt4.4 and Python 2.5
  3. # also tetsed with PyQt4.5 and Python 3.0
  4. # vegaseat
  5.  
  6. import sys
  7. # expect minimal namespace conflicts
  8. from PyQt4.QtCore import *
  9. from PyQt4.QtGui import *
  10.  
  11. class MoviePlayer(QWidget):
  12. def __init__(self, parent=None):
  13. QWidget.__init__(self, parent)
  14. # setGeometry(x_pos, y_pos, width, height)
  15. self.setGeometry(200, 200, 400, 300)
  16. self.setWindowTitle("QMovie to show animated gif")
  17.  
  18. # set up the movie screen on a label
  19. self.movie_screen = QLabel()
  20. # expand and center the label
  21. self.movie_screen.setSizePolicy(QSizePolicy.Expanding,
  22. QSizePolicy.Expanding)
  23. self.movie_screen.setAlignment(Qt.AlignCenter)
  24.  
  25. main_layout = QVBoxLayout()
  26. main_layout.addWidget(self.movie_screen)
  27. self.setLayout(main_layout)
  28.  
  29. # use an animated gif file you have in the working folder
  30. # or give the full file path
  31. movie = QMovie("AG_Dog.gif", QByteArray(), self)
  32. movie.setCacheMode(QMovie.CacheAll)
  33. movie.setSpeed(100)
  34. self.movie_screen.setMovie(movie)
  35. movie.start()
  36.  
  37.  
  38. app = QApplication(sys.argv)
  39. player = MoviePlayer()
  40. player.show()
  41. sys.exit(app.exec_())
Attached Images
 
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Python GUI Programming

 
1
  #18
Jun 13th, 2009
Draw a simple bar chart with PyQT:
  1. # use PyQT to draw a simple vertical bar chart
  2. # tested with PyQT4.5 and Python3.0
  3. # ene
  4.  
  5. import sys
  6. # simplified import, hopefully no namespace conflicts
  7. from PyQt4.QtCore import *
  8. from PyQt4.QtGui import *
  9.  
  10. class BarChart(QWidget):
  11. def __init__(self, data, parent=None):
  12. QWidget.__init__(self, parent)
  13. # setGeometry(x_pos, y_pos, width, height)
  14. self.setGeometry(300, 300, 360, 320)
  15. self.setWindowTitle('A Simple Bar Chart')
  16. self.data = data
  17.  
  18. def paintEvent(self, event):
  19. painter = QPainter()
  20. painter.begin(self)
  21.  
  22. # set color and width of line drawing pen
  23. painter.setPen(QPen(Qt.black, 2))
  24.  
  25. # drawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
  26. # draw the baseline
  27. painter.drawLine(20, 280, 340, 280)
  28.  
  29. # set up color and width of the bars
  30. width = 20
  31. painter.setPen(QPen(Qt.red, width))
  32. delta = width + 5
  33. x = 30
  34. for y in self.data:
  35. # correct for width
  36. y1 = 280 - width/2
  37. y2 = y1 - y + width/2
  38. # draw each bar
  39. painter.drawLine(x, y1, x, y2)
  40. # add values to the top of each bar
  41. s = str(y)
  42. painter.drawText(x-8, y2-15, s)
  43. x += delta
  44.  
  45. painter.end()
  46.  
  47.  
  48. # data to be graphed
  49. data = [30, 45, 80, 150, 220, 180, 110, 75, 50, 35, 20, 10]
  50. app = QApplication(sys.argv)
  51. bc = BarChart(data)
  52. bc.show()
  53. app.exec_()
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,514
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 168
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Python GUI Programming

 
1
  #19
Jun 17th, 2009
PyQT has an interesting widget called a dial (circular slider). Here is a simple applcation:
  1. # use a PyQT QDial knob to select a temperature
  2. # show Celsius and corresponding Fahrenheit values
  3. # as the knob is rotated
  4. # tested with PyQT4.5 and Python3.0
  5. # ene
  6.  
  7. import sys
  8. # has minimal namespace conflicts
  9. from PyQt4.QtCore import *
  10. from PyQt4.QtGui import *
  11.  
  12. class MyFrame(QWidget):
  13. def __init__(self, parent=None):
  14. QWidget.__init__(self, parent)
  15. # setGeometry(x_pos, y_pos, width, height)
  16. self.setGeometry(150, 150, 328, 440)
  17. self.setWindowTitle('Convert Temperature')
  18.  
  19. self.dial = QDial(self)
  20. self.dial.setGeometry(QRect(10, 20, 311, 351))
  21. self.dial.setMinimum(-50)
  22. self.dial.setMaximum(310)
  23. self.dial.setPageStep(10)
  24. # initial dial pointer position
  25. dial_pos = 50
  26. self.dial.setSliderPosition(dial_pos)
  27. self.dial.setWrapping(True)
  28. self.dial.setNotchTarget(3.6)
  29. self.dial.setNotchesVisible(True)
  30.  
  31. self.label_c = QLabel(self)
  32. self.label_c.setGeometry(QRect(30, 390, 121, 31))
  33. font = QFont()
  34. font.setPointSize(11)
  35. self.label_c.setFont(font)
  36. self.label_c.setAlignment(Qt.AlignCenter)
  37.  
  38. self.label_f = QLabel(self)
  39. self.label_f.setGeometry(QRect(170, 390, 131, 31))
  40. font = QFont()
  41. font.setPointSize(11)
  42. self.label_f.setFont(font)
  43. self.label_f.setAlignment(Qt.AlignCenter)
  44.  
  45. # start up
  46. self.show_temps()
  47. # update show_temps()
  48. self.connect(self.dial, SIGNAL("sliderMoved(int)"),
  49. self.show_temps)
  50.  
  51. def show_temps(self):
  52. """
  53. get the C value from the dial label
  54. calculate F value and show
  55. """
  56. c = float(self.dial.value())
  57. s_c = "%0.1f Celsius" % c
  58. self.label_c.setText(s_c)
  59. f = c*9/5.0 + 32
  60. s_f = "%0.1f Fahrenheit" % f
  61. self.label_f.setText(s_f)
  62.  
  63.  
  64. app = QApplication(sys.argv)
  65. frame = MyFrame()
  66. frame.show()
  67. sys.exit(app.exec_())
Sorry, I am having real problems with my HP notebook, the keyboard is of very poor quality and misses keystrokes a lot!
Last edited by vegaseat; Jun 18th, 2009 at 7:33 pm. Reason: Bug removed at Ene's request
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,275
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 174
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Python GUI Programming

 
1
  #20
Jun 20th, 2009
An example how to use an image as a background. In order to make added text transparent, use the Tkinter canvas:
  1. # use a Tkinter canvas for a background image
  2. # add transparent text and other widgets
  3. # with Python3 use import tkinter as tk
  4. # snee
  5.  
  6. import Tkinter as tk
  7.  
  8. root = tk.Tk()
  9. root.title('background image')
  10.  
  11. # pick a .gif image file you have in the working directory
  12. bg_image = tk.PhotoImage(file="Flowers.gif")
  13. w = bg_image.width()
  14. h = bg_image.height()
  15.  
  16. # size the window so the image will fill it
  17. root.geometry("%dx%d+0+0" % (w, h))
  18.  
  19. cv = tk.Canvas(width=w, height=h)
  20. cv.pack(side='top', fill='both', expand='yes')
  21. cv.create_image(0, 0, image=bg_image, anchor='nw')
  22.  
  23. # add canvas text at coordinates x=15, y=30
  24. # anchor='nw' implies upper left corner coordinates
  25. cv.create_text(15, 30, text="Python Greetings", fill="red", anchor='nw')
  26.  
  27. # now some button widgets
  28. btn1 = tk.Button(cv, text="Click")
  29. btn1.pack(side='left', padx=10, pady=5, anchor='sw')
  30.  
  31. btn2 = tk.Button(cv, text="Quit")
  32. btn2.pack(side='left', padx=10, pady=5, anchor='sw')
  33.  
  34. root.mainloop()
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC