943,697 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 71708
  • Python RSS
You are currently viewing page 7 of this multi-page discussion thread; Jump to the first page
Sep 7th, 2009
1

Re: Python GUI Programming

A similar table, this time we use PyQT's QTableView and QAbstractTableModel which allows the items in the table to be sorted by simply clicking on the header titles:
python Syntax (Toggle Plain Text)
  1. # use PyQT's QTableView and QAbstractTableModel
  2. # to present tabular data
  3. # allow sorting by clicking on the header title
  4. # tested with Python 3.1.1 and PyQT 4.5.2
  5. # ene
  6.  
  7. import operator
  8. from PyQt4.QtCore import *
  9. from PyQt4.QtGui import *
  10.  
  11. class MyWindow(QWidget):
  12. def __init__(self, data_list, header, *args):
  13. QWidget.__init__(self, *args)
  14. # setGeometry(x_pos, y_pos, width, height)
  15. self.setGeometry(300, 200, 420, 250)
  16. self.setWindowTitle("Exploring PyQT's QTableView")
  17.  
  18. table_model = MyTableModel(self, data_list, header)
  19. table_view = QTableView()
  20. table_view.setModel(table_model)
  21. # enable sorting
  22. table_view.setSortingEnabled(True)
  23.  
  24. layout = QVBoxLayout(self)
  25. layout.addWidget(table_view)
  26. self.setLayout(layout)
  27.  
  28.  
  29. class MyTableModel(QAbstractTableModel):
  30. def __init__(self, parent, mylist, header, *args):
  31. QAbstractTableModel.__init__(self, parent, *args)
  32. self.mylist = mylist
  33. self.header = header
  34.  
  35. def rowCount(self, parent):
  36. return len(self.mylist)
  37.  
  38. def columnCount(self, parent):
  39. return len(self.mylist[0])
  40.  
  41. def data(self, index, role):
  42. if not index.isValid():
  43. return QVariant()
  44. elif role != Qt.DisplayRole:
  45. return QVariant()
  46. return QVariant(self.mylist[index.row()][index.column()])
  47.  
  48. def headerData(self, col, orientation, role):
  49. if orientation == Qt.Horizontal and role == Qt.DisplayRole:
  50. return QVariant(self.header[col])
  51. return QVariant()
  52.  
  53. def sort(self, col, order):
  54. """sort table by given column number col"""
  55. self.emit(SIGNAL("layoutAboutToBeChanged()"))
  56. self.mylist = sorted(self.mylist,
  57. key=operator.itemgetter(col))
  58. if order == Qt.DescendingOrder:
  59. self.mylist.reverse()
  60. self.emit(SIGNAL("layoutChanged()"))
  61.  
  62.  
  63. header = ['First Name', 'Last Name', 'Age', 'Weight']
  64. # a list of (name, age, weight) tuples
  65. data_list = [
  66. ('Heidi', 'Kalumpa', '36', '127'),
  67. ('Frank', 'Maruco', '27', '234'),
  68. ('Larry', 'Pestraus', '19', '315'),
  69. ('Serge', 'Romanowski', '59', '147'),
  70. ('Carolus', 'Arm', '94', '102'),
  71. ('Michel', 'Sargnagel', '21', '175')
  72. ]
  73.  
  74. app = QApplication([])
  75. win = MyWindow(data_list, header)
  76. win.show()
  77. app.exec_()
Not sure what is going on with the code tags??? Ah, it fixed itself!
Last edited by Ene Uran; Sep 7th, 2009 at 4:15 pm.
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Sep 9th, 2009
0

Re: Python GUI Programming

Want to add font and color to PyQT's label text? Here is one way to do just that ...
python Syntax (Toggle Plain Text)
  1. # adding font and color to PyQT's QLabel widget text
  2. # vegaseat
  3.  
  4. from PyQt4.QtCore import *
  5. from PyQt4.QtGui import *
  6.  
  7. class MyForm(QWidget):
  8. def __init__(self):
  9. QWidget.__init__(self)
  10. # setGeometry(x_pos, y_pos, width, height)
  11. self.setGeometry(100, 150, 320, 100)
  12. self.setWindowTitle("font and color")
  13.  
  14. text = " QLabel text with font and color "
  15. label = QLabel(text)
  16.  
  17. # QFont(family, pointSize, weight, italic)
  18. # weight QFont.Light=25, QFont.Normal=50, QFont.Bold=75
  19. # pointSize=12, weight=50, italic=False by default
  20. font = QFont("Times", 32, QFont.Bold, True)
  21. label.setFont(font)
  22.  
  23. # set the foreground and background colors of the label
  24. fg = "QLabel {color:red}"
  25. bg = "QLabel {background-color:yellow}"
  26. label.setStyleSheet( fg+bg )
  27.  
  28. # use grid layout
  29. grid = QGridLayout()
  30. # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
  31. grid.addWidget(label)
  32. self.setLayout(grid)
  33.  
  34.  
  35. app = QApplication([])
  36. form = MyForm()
  37. form.show()
  38. app.exec_()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 14th, 2009
0

Re: Python GUI Programming

Well, PyGame is out for Python 3.1, so I downloaded/installed the Windows installer and gave it a quick test ...
python Syntax (Toggle Plain Text)
  1. # experiments with module pygame
  2. # bounce a red ball whose image is stored in this code
  3. # pygame from: http://www.pygame.org/
  4. # win binary installed: pygame-1.9.1.win32-py3.1.msi
  5. # tested with Python 3.1.1 and Pygame 1.9.1
  6. # vegaseat 14sep2009
  7.  
  8. import pygame as pg
  9. import base64
  10.  
  11. """
  12. # use this Python3 program to create a base64 encoded image string
  13. # (base64 encoding produces a readable string from a binary image)
  14. # then copy and paste the result into your pygame program ...
  15. import base64
  16. gif_file = "ball_r.gif"
  17. gif_bytes = open(gif_file, 'rb').read()
  18. b64_bytes = base64.encodebytes(gif_bytes)
  19. # decode <class 'bytes'> bytestring to string
  20. b64_str = b64_bytes.decode("utf8")
  21. print( "gif64='''\\\n" + b64_str + "'''" )
  22. """
  23.  
  24. gif64='''\
  25. R0lGODlhQABAAPcAACEBAY8DA9wQILcED1ECAqMECOsaL8oKGTgBAXADA5kEBeQVJ8EIFK0EC+wg
  26. NS8BAWUCAtMOH0gCAoQDAykBAZkEBNwSJsEGEFsCAq0ECOwdNdMMGkABAXoDA6MEBuUXLsoJFbcE
  27. DPIgNQAAAJ0FBAAAAAAAAAAAAAAABQAAAAAAAAAAAPEGCt0FBQQAAAAAAF4CBAkAAN8FBVUCAgAA
  28. AgAAAAAAAAAAAAEBgAAAAQUAAwIC7gAAKt0FBQUBZgAAAAAABgAAAAAAAAAAAAsAAN4FBQQAAAAA
  29. AOgPDmoCAu8GBlUCAmoDBwgAAOsFBVUCAvIGRfIGDfMHz/IGOhgGZXUDA+sFBVUCAugMoQoCwu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mGWB5NsgleBile5QK4Z86YoG
  57. Wj5QGfNskEgqNEhHpEKVDoXgAyLQGFd64wADLOAAHijLWXBYGB02pSZSyclO8LUAoAjlAkU5ikq8
  58. yLskMuUgHgGJSBJAkpOkZCVu5CIbL6KSBxgxLWvco0sCAgA7
  59. '''
  60.  
  61. # encode string to <class 'bytes'>, needed for Python3
  62. # comment out if you are using Python2
  63. gif64 = gif64.encode("utf8")
  64.  
  65. # convert back to a binary image to save to a file in the working directory
  66. ball = base64.b64decode(gif64)
  67. fout = open("ball_r.gif","wb")
  68. fout.write(ball)
  69. fout.close()
  70.  
  71. # initialize pygame
  72. pg.init()
  73.  
  74. # now you can use the gif file you just saved
  75. image_file = "ball_r.gif"
  76.  
  77. # image moves [x, y] at a time
  78. im_dir = [2, 1]
  79.  
  80. # pygame uses an RGB color tuple
  81. black = (0,0,0)
  82. # screen width and height
  83. sw = 600
  84. sh = 480
  85. # create a screen
  86. screen = pg.display.set_mode((sw, sh))
  87. # give the screen a title
  88. pg.display.set_caption('bouncing ball (press escape to exit)')
  89.  
  90. # load the ball image file
  91. image = pg.image.load(image_file).convert()
  92. # get the rectangle that the image occupies
  93. im_rect = image.get_rect()
  94.  
  95. # the event loop also loops the animation code
  96. while True:
  97. pg.event.pump()
  98. keyinput = pg.key.get_pressed()
  99. # exit on corner 'x' click or escape key press
  100. if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT):
  101. raise SystemExit
  102.  
  103. # set the move
  104. im_rect = im_rect.move(im_dir)
  105. # detect the boundaries and change directions
  106. # left/right boundaries are 0 to sreen width
  107. if im_rect.left < 0 or im_rect.right > sw:
  108. im_dir[0] = -im_dir[0]
  109. # top/bottom boundaries are 0 to screen height
  110. if im_rect.top < 0 or im_rect.bottom > sh:
  111. im_dir[1] = -im_dir[1]
  112. # this erases the old sreen with black
  113. screen.fill(black)
  114. # put the image on the screen
  115. screen.blit(image, im_rect)
  116. # update screen
  117. pg.display.flip()
Last edited by vegaseat; Sep 14th, 2009 at 8:29 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 14th, 2009
0

Re: Python GUI Programming

Here is a simple Pygame example showing an approach to a resizable window ...
python Syntax (Toggle Plain Text)
  1. # create a resizable pygame window
  2. # tested with Python 3.1.1 and Pygame 1.9.1
  3. # vegaseat
  4.  
  5. import pygame as pg
  6.  
  7. def create_window(width, height):
  8. """create a width x height resizable window/frame"""
  9. win = pg.display.set_mode((width, height), pg.RESIZABLE)
  10. # optional fill bg red, default is black
  11. win.fill((255, 0, 0))
  12. # optional title info
  13. sf = "size x=%s y=%s" % (width, height)
  14. pg.display.set_caption(sf)
  15.  
  16. # any extra code here ...
  17. # draw a white circle
  18. white = (255, 255, 255)
  19. # center can be fixed or calculated for resize
  20. center = (150, 150)
  21. radius = 100
  22. pg.draw.circle(win, white, center, radius)
  23.  
  24. pg.display.flip()
  25. return win
  26.  
  27.  
  28. pg.init()
  29.  
  30. width = 300
  31. height = 200
  32. win = create_window(width, height)
  33.  
  34. # event loop and exit conditions (windows titlebar x click)
  35. while True:
  36. for event in pg.event.get():
  37. if event.type == pg.VIDEORESIZE:
  38. width, height = event.size
  39. # redraw win in new size
  40. win = create_window(width, height)
  41. print(win.get_size()) # test
  42. if event.type == pg.QUIT:
  43. raise SystemExit
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 15th, 2009
2

Re: Python GUI Programming

Yes Gloria, Tkinter has a combo box, but it's called an option menu. Here is an example:
python Syntax (Toggle Plain Text)
  1. # using Tkinter's Optionmenu() as a combobox
  2.  
  3. try:
  4. # Python2
  5. import Tkinter as tk
  6. except ImportError:
  7. # Python3
  8. import tkinter as tk
  9.  
  10. def select():
  11. sf = "value is %s" % var.get()
  12. root.title(sf)
  13. # optional
  14. color = var.get()
  15. root['bg'] = color
  16.  
  17.  
  18. root = tk.Tk()
  19. # use width x height + x_offset + y_offset (no spaces!)
  20. root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
  21. root.title("tk.Optionmenu as combobox")
  22.  
  23. var = tk.StringVar(root)
  24. # initial value
  25. var.set('red')
  26.  
  27. choices = ['red', 'green', 'blue', 'yellow','white', 'magenta']
  28. option = tk.OptionMenu(root, var, *choices)
  29. option.pack(side='left', padx=10, pady=10)
  30.  
  31. button = tk.Button(root, text="check value slected", command=select)
  32. button.pack(side='left', padx=20, pady=10)
  33.  
  34. root.mainloop()
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Sep 16th, 2009
0

Re: Python GUI Programming

Talking about Gloria, I thought I better post that here, in case someone is looking for a Tkinter GUI toolkit progressbar ...
python Syntax (Toggle Plain Text)
  1. # explore the ttk.Progressbar of the Tkinter module ttk
  2. # ttk is included with Python 3.1.1
  3. # vegaseat
  4.  
  5. import tkinter as tk
  6. from tkinter import ttk
  7.  
  8. def click(event):
  9. # can be a float
  10. increment = 3.4
  11. pbar.step(increment)
  12.  
  13.  
  14. root = tk.Tk()
  15. root.title('ttk.Progressbar')
  16.  
  17. pbar = ttk.Progressbar(root, length=300)
  18. pbar.pack(padx=5, pady=5)
  19.  
  20. btn = tk.Button(root, text="Click to advance progress bar")
  21. # bind to left mouse button click
  22. btn.bind("<Button-1>", click)
  23. btn.pack(pady=10)
  24.  
  25. root.mainloop()
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 16th, 2009
0

Re: Python GUI Programming

There is the Visual Python specialized GUI toolkit, used mostly for 3D modeling. You can draw an object and then drag it in space with the cursor with the right mouse button pressed. Objects can also be animated. Here is a short sample ...
python Syntax (Toggle Plain Text)
  1. # draw cones in space
  2. # press the right mouse button and use cursor to rotate the object
  3. # experiments with visual Python (VPython) from: http://vpython.org/
  4. # used VPython-Win-Py2.6-5.12.exe for Python26
  5. # needs and comes with numpy
  6. """
  7. cone(pos=(0,0,0), axis=(1,0,0), radius=1, color=(0,0,0))
  8. color (red, green, blue) color values 0.0 to 1.0
  9. default is white = (1,1,1)
  10. """
  11.  
  12. import visual as vs
  13.  
  14. vs.scene.width = 500
  15. vs.scene.height = 500
  16. vs.scene.title = "draw 3 cones (drag with right mouse button)"
  17.  
  18. # avoid autoscale (autoscale default=True)
  19. vs.scene.autoscale = False
  20.  
  21. # axis x=8 points right
  22. cone1 = vs.cone(pos=(0,0,0), axis=(8,0,0), radius=4)
  23. cone1.color = vs.color.green
  24.  
  25. # axis x=-8 points left
  26. cone2 = vs.cone(pos=(0,0,0), axis=(-8,0,0), radius=4)
  27. cone2.color = vs.color.red
  28.  
  29. # pos y=-6 is below center and axis y=2.4 points up from there
  30. cone3 = vs.cone(pos=(0,-6,0), axis=(0,2.4,0), radius=4)
  31. cone3.color = (0.0, 0.9, 1.0)
Last edited by vegaseat; Sep 16th, 2009 at 8:12 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 26th, 2009
2

Re: Python GUI Programming

There is another Python version called IronPython that uses Python syntax. It runs independent from the normal CPython version and allows access to the large GUI libraries of .NET and Mono. Here is an example:
python Syntax (Toggle Plain Text)
  1. # create a window with a button and click event using ironpython
  2. # ironpython gives access to the Windows .NET or Linux Mono libraries
  3. # download ironpython from:
  4. # http://www.codeplex.com/ironpython
  5. # tutorial at:
  6. # http://www.zetcode.com/tutorials/ironpythontutorial/
  7. #
  8. # to distinguish the filename from normal Python use prefix ip_
  9. # if you save this file as "ip_buttonWin1.py"
  10. # compile it with something like:
  11. # C:\IronPython 2.6\ipy.exe "ip_buttonWin1.py"
  12. #
  13. # clr -> Common Language Runtime
  14.  
  15. import clr
  16.  
  17. clr.AddReference("System.Windows.Forms")
  18. clr.AddReference("System.Drawing")
  19.  
  20. from System.Windows.Forms import Application, Form, Button, ToolTip
  21. from System.Drawing import Size, Point
  22.  
  23. class IForm(Form):
  24.  
  25. def __init__(self):
  26. # set form title, position, size
  27. self.Text = 'Button'
  28. self.CenterToScreen()
  29. self.Size = Size(300, 150)
  30.  
  31. btn = Button()
  32. btn.Parent = self
  33. btn.Text = "Quit"
  34. btn.Location = Point(50, 50)
  35. # click on the button to call OnClick()
  36. btn.Click += self.OnClick
  37. # mouse over button calls OnEnter()
  38. btn.MouseEnter += self.OnEnter
  39.  
  40. # optional tooltip
  41. tooltip = ToolTip()
  42. # tooltip for the button
  43. tooltip.SetToolTip(btn, "Don't be a Quitter")
  44.  
  45. def OnClick(self, sender, args):
  46. self.Close()
  47.  
  48. def OnEnter(self, sender, args):
  49. #print sender, type(sender)
  50. self.Text = "mouse entered button area"
  51.  
  52.  
  53. Application.Run(IForm())
Since i have a Windows XP machine I installed
IronPython-2.6.msi
and for the .NET framework (free from MicroSoft)
NetFx20SP1_x86.exe

See the details in file Readme.html that comes with the installation.
Last edited by Ene Uran; Sep 26th, 2009 at 2:07 pm.
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Oct 1st, 2009
1

Re: Python GUI Programming

Here we use the Python Image Library (PIL) and Tkinter to display the images inside a folder as thumbnails ...
python Syntax (Toggle Plain Text)
  1. # explore Tkinter and PIL to create a list of photos
  2. # that can be displayed as thumbnails
  3. # tested with Python25 by vegaseat
  4.  
  5. import Tkinter as tk
  6. from PIL import ImageTk, Image
  7. import glob
  8. import random
  9.  
  10. # make sure you have a folder with some jpeg pictures
  11. folder = "./Pics_jpg"
  12. # create a list of .jpg images that are in this folder
  13. pic_list = glob.glob(folder+'/*.jpg')
  14.  
  15. root = tk.Tk()
  16. root.title(folder)
  17.  
  18. label_list = []
  19. photo_list = []
  20. for pathname in pic_list:
  21. image = Image.open(pathname)
  22. # create a thumbnail of each image
  23. # width=100 height=150
  24. image.thumbnail((100, 150), Image.ANTIALIAS)
  25. # convert to something Tkinter can handle
  26. photo = ImageTk.PhotoImage(image)
  27. # the photo list is needed for labels to retain photos!
  28. photo_list.append(photo)
  29. label_list.append(tk.Label(image=photo))
  30.  
  31. # optionally random shuffle the label_list
  32. #random.shuffle(label_list)
  33.  
  34. # display the thumbnails in rows of pics_per_row pictures
  35. pics_per_row = 4
  36. row = col = 0
  37. for label in label_list:
  38. label.grid(row=row, column=col)
  39. col += 1
  40. if col >= pics_per_row:
  41. col = 0
  42. row += 1
  43.  
  44. root.mainloop()
If you also have GIF images in that folder and want to display them too use:
pic_list = glob.glob(folder+'/*.jpg') + glob.glob(folder+'/*.gif')
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 6th, 2009
1

Which GUI

When I started with python I used Tkinter as it came with the implementation (Windows version of python).

Later I was looking for something more powerful (or so I thought) and selected wx. For many years I used wx and was reasonably happy with it. But when I started using Linux (Mint) and running the software I developed both on Windows and Linux I found that wx looked different and in some cases behaved different on Linux and Windows. A case in point is the wx.Choice widget which on Windows leaves the entry box empty until you select an item from the list (the behaviour I wanted) but on Linux the entry box displayed the first item in the list, even though it was not selected! And because this was financial software led to some very undesirable consequences when uses thought they had already selected an item from the Choice widget.

After researching this for a while I found too many cases where there needed to be code changes between a Linux and Windows version using wx - not important if you don't write for both platforms, but a pain otherwise.

I returned to Tkinter and am still using it. It is simpler and in its basic implementation has fewer bells and whistles, but in some ways I prefer that and build my own widgets from basic components. Now at least my applications work the same and the layout for both Windows and Linux is almost the same.

I have never been that comfortable with grids as supplied by a particular gui, and back in my VB days I built my own grid box using a matrix of labels. So I decided to transfer that design to python using Tkinter labels. I find that way I can add features when I need them (many grid widgets are too complicated for my simple use) and can make them operate the way I wish. I find an array of labels works well for me.
Reputation Points: 19
Solved Threads: 0
Newbie Poster
jimscafe is offline Offline
2 posts
since Apr 2009
Message:
Previous Thread in Python Forum Timeline: cx_Freeze error
Next Thread in Python Forum Timeline: nested for loop break





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC