944,103 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 71880
  • Python RSS
You are currently viewing page 8 of this multi-page discussion thread; Jump to the first page
Oct 13th, 2009
3
Re: Python GUI Programming
Creating a simple shadow effect around a Tkinter frame ...
python Syntax (Toggle Plain Text)
  1. # create a frame with a shadow effect border
  2. # using overlapping frames
  3. # vegaseat
  4.  
  5. try:
  6. # Python2
  7. import Tkinter as tk
  8. except ImportError:
  9. # Python3
  10. import tkinter as tk
  11.  
  12. root = tk.Tk()
  13. w = 320
  14. h = 220
  15. x = 150
  16. y = 100
  17. # use width x height + x_offset + y_offset (no spaces!)
  18. root.geometry("%dx%d+%d+%d" % (w, h, x, y))
  19. root.title("shadow effect border")
  20.  
  21. frame1 = tk.Frame(root, bg='grey', width=w-30, height=h-30)
  22. frame1.place(x=20, y=20)
  23.  
  24. frame2 = tk.Frame(root, bg='yellow', width=w-30, height=h-30)
  25. frame2.place(x=10, y=10)
  26.  
  27. root.mainloop()
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 14th, 2009
2
Re: Python GUI Programming
Ah, the ever so popular Tkinter GUI toolkit. This is the code to get size (width x height) and position (x + y coordinates of the upper left corner of the window in the display screen) information of the Tkinter root window ...
python Syntax (Toggle Plain Text)
  1. # show width and height of Tkinter's root window
  2. # vegaseat
  3.  
  4. try:
  5. # Python2
  6. import Tkinter as tk
  7. except ImportError:
  8. # Python3
  9. import tkinter as tk
  10.  
  11. root = tk.Tk()
  12. w = 460
  13. h = 320
  14. x = 150
  15. y = 100
  16. # use width x height + x_offset + y_offset (no spaces!)
  17. root.geometry("%dx%d+%d+%d" % (w, h, x, y))
  18.  
  19. # update is needed
  20. root.update()
  21. geo = root.geometry()
  22. print(geo) # 460x320+150+100
  23. width = root.winfo_width() # 460
  24. print(width)
  25. height = root.winfo_height() # 320
  26. print(height)
  27.  
  28. root.mainloop()
Last edited by vegaseat; Oct 14th, 2009 at 5:18 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 14th, 2009
1
Re: Python GUI Programming
Here is typical code that I use with the py2exe module to convert Tkinter programs to an executable package for Windows computers ...
python Syntax (Toggle Plain Text)
  1. """
  2. Simple py2exe version used for Tkinter programs.
  3. Run this program to create a windows exe file with py2exe.
  4. Run it in a folder that als contains your source code file.
  5.  
  6. It will create 2 folders named build and dist.
  7.  
  8. The build folder is temporary info and can be deleted.
  9.  
  10. Distribute whatever is in the dist folder.
  11.  
  12. Your library.zip file contains your optimized byte code, and all
  13. needed modules. This file together with the Python interpreter
  14. (eg. Python25.dll) should accompany the created executable file.
  15. Note that you might be able to share this large library file with
  16. other Python/Tkinter based .exe files.
  17.  
  18. The MSVCR71.dll can be distributed and is often already in the
  19. Windows/system32 folder.
  20.  
  21. w9xpopen.exe is needed for os.popen() only, can be deleted otherwise.
  22. """
  23.  
  24. from distutils.core import setup
  25. import py2exe
  26. import sys
  27.  
  28. sys.argv.append("py2exe")
  29. sys.argv.append("-q")
  30.  
  31. # insert your own source code filename below ...
  32. code_file = 'Tk_ParResist1.pyw'
  33.  
  34. # replace windows with console for a console program
  35. setup(windows = [{"script": code_file}])
Should work with Python26 if you installed the proper py2exe module. Since Python26 uses a different C compiler, msvcr71.dll changes to msvcr90.dll and of course the interpreter is Python26.dll.
Last edited by vegaseat; Oct 14th, 2009 at 5:54 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 23rd, 2009
2
Re: Python GUI Programming
One way to display a colorful message with the ever so popular PyQT GUI toolkit (works with Python2 and Python3) ...
python Syntax (Toggle Plain Text)
  1. # show a colorful splash message for a set time then quit
  2. # tested with PyQT45 by vegaseat
  3.  
  4. from PyQt4.QtCore import *
  5. from PyQt4.QtGui import *
  6.  
  7. def do_html(text, color='black', size=3):
  8. """create a line of html code for text with color and size"""
  9. sf = "<FONT color=%s size=%d>%s</FONT>"
  10. return sf % (color, size, text)
  11.  
  12. # build up simple HTML code ...
  13. # text between <B> and </B> is bold
  14. # <BR> inserts a line break (new line)
  15. html = ""
  16. html += '<BR>'
  17. orange = "#FFBA00" # gives a better orange color
  18. color_list = ['red', orange, 'yellow', 'green', 'blue']
  19. ix = 0
  20. for c in 'WE LOVE RAINBOWS':
  21. # make character c bold
  22. c = "<B>" + c + "</B>"
  23. if ix >= len(color_list):
  24. ix = 0
  25. html += do_html(c, color_list[ix], 7)
  26. ix += 1
  27. html += '<BR>'
  28.  
  29. # create a QT GUI application
  30. app = QApplication([])
  31. label = QLabel(html)
  32. # show label without frame
  33. # comment line out if you want a frame
  34. label.setWindowFlags(Qt.SplashScreen)
  35. label.show()
  36. # show for x milliseconds, then quit
  37. x = 5000
  38. QTimer.singleShot(x, app.quit)
  39. app.exec_()
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 31st, 2009
2
Re: Python GUI Programming
The Text widget of the Tkinter GUI toolkit is the start of a simple text editor. Here we explore how to get the line (row) and column numbers of the text insertion point ...
python Syntax (Toggle Plain Text)
  1. # explore Tkinter's Text widget
  2. # get the line and column values of the text insertion point
  3. # vegaseat
  4.  
  5. import Tkinter as tk
  6.  
  7. def get_position(event):
  8. """get the line and column number of the text insertion point"""
  9. line, column = text.index('insert').split('.')
  10. s = "line=%s column=%s" % (line, column)
  11. root.title(s)
  12.  
  13.  
  14. root= tk.Tk()
  15. root.title('start typing')
  16. text = tk.Text(root, width=40, height=10)
  17. text.bind("<KeyRelease>", get_position)
  18. text.pack()
  19. # start cursor in text area
  20. text.focus()
  21.  
  22. root.mainloop()
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 19th, 2009
1
Re: Python GUI Programming
Here is modified (also added needed delay) and commented code from the pygame tutorial that shows how to load one image onto rectangle object and move the object:
python Syntax (Toggle Plain Text)
  1. # use pygame to bounce/move loaded image around the screen
  2.  
  3. import sys, pygame
  4.  
  5. pygame.init()
  6.  
  7. size = width, height = 320, 240
  8. # this determines the move direction/speed in pixels
  9. # speed[0] left or right
  10. # speed[1] up or down
  11. speed = [2, 2]
  12. # color uses r, g, b tuple
  13. black = 0, 0, 0
  14. # white works better here
  15. white = 255, 255, 255
  16.  
  17. # create the window
  18. screen = pygame.display.set_mode(size)
  19. # give the window a title
  20. pygame.display.set_caption("watch the beach ball bounce")
  21.  
  22. # make sure the image file is in the working directory
  23. # or give full path name
  24. ball = pygame.image.load("ball.bmp")
  25. # create rectangle object you can move
  26. # it is used to put the image on
  27. ballrect = ball.get_rect()
  28.  
  29. while True:
  30. for event in pygame.event.get():
  31. # window corner x will exit
  32. if event.type == pygame.QUIT:
  33. sys.exit()
  34. # move the rectangle object
  35. ballrect = ballrect.move(speed)
  36. # change direction if left or right boundry is reached
  37. if ballrect.left < 0 or ballrect.right > width:
  38. speed[0] = -speed[0]
  39. # change direction if top or bottom boundry is reached
  40. if ballrect.top < 0 or ballrect.bottom > height:
  41. speed[1] = -speed[1]
  42. # clear the screen with white background
  43. screen.fill(white)
  44. # put the image on the rectangle object
  45. screen.blit(ball, ballrect)
  46. # update screen
  47. pygame.display.flip()
  48. # small time delay
  49. milliseconds = 20
  50. pygame.time.delay(milliseconds)
The image used here is attached below, just download it into your working directory. Also click on Toggle Plain Text, select code and copy it to your IDE's editor, save it to the same working directory your image is in, then run it from the IDE. I use PyScripter (Windows) IDE, but you can use IDLE or something.
Attached Images
File Type: bmp ball.bmp (13.2 KB, 30 views)
Last edited by bumsfeld; Nov 19th, 2009 at 4:45 pm. Reason: IDE
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Nov 22nd, 2009
1
Re: Python GUI Programming
A simple way to add color highlighted text to the Tkinter Text() widget ...
python Syntax (Toggle Plain Text)
  1. # multiple color text with Tkinter using widget Text() and tags
  2. # vegaseat
  3.  
  4. try:
  5. # Python2
  6. import Tkinter as tk
  7. except ImportError:
  8. # Python3
  9. import tkinter as tk
  10.  
  11. def color_text(edit, tag, word, fg_color='black', bg_color='white'):
  12. # add a space to the end of the word
  13. word = word + " "
  14. edit.insert('end', word)
  15. end_index = edit.index('end')
  16. begin_index = "%s-%sc" % (end_index, len(word) + 1)
  17. edit.tag_add(tag, begin_index, end_index)
  18. edit.tag_config(tag, foreground=fg_color, background=bg_color)
  19.  
  20.  
  21. root = tk.Tk()
  22. root.geometry("600x200")
  23.  
  24. edit = tk.Text(root)
  25. edit.pack()
  26.  
  27. text = "Up the hill went Jack and Jill, down fell Jill and cried!"
  28. # create a list of single words
  29. word_list = text.split()
  30. #print( word_list ) # test
  31.  
  32. # pick word to be colored
  33. myword1 = 'Jack'
  34. myword2 = 'Jill'
  35. # create a list of unique tags
  36. tags = ["tg" + str(k) for k in range(len(word_list))]
  37. for ix, word in enumerate(word_list):
  38. # word[:len(myword)] for word ending with a punctuation mark
  39. if word[:len(myword1)] == myword1:
  40. color_text(edit, tags[ix], word, 'blue')
  41. elif word[:len(myword2)] == myword2:
  42. color_text(edit, tags[ix], word, 'red', 'yellow')
  43. else:
  44. color_text(edit, tags[ix], word)
  45.  
  46. root.mainloop()
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 22nd, 2009
0
Re: Python GUI Programming
Tkinter can be used to write programs that use pop-up dialogs for input and output. The nice thing is that the input dialogs can restrict data input to integer, float or string input with options for initial, min and max values. Here is a small example ...
Python Syntax (Toggle Plain Text)
  1. # use Tkinter popup dialogs for input and output
  2. # see:
  3. # http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/
  4. # TkIntro/introduction/intro08.htm
  5. # simple dialogs are:
  6. # askfloat, askinteger, and askstring
  7. # messagebox dialogs are:
  8. # showinfo, showwarning, showerror, askquestion, askokcancel,
  9. # askyesno, askretrycancel
  10. # vegaseat
  11.  
  12. try:
  13. # Python2
  14. import Tkinter as tk
  15. import tkSimpleDialog as tksd
  16. import tktkMessageBox as tkmb
  17. except ImportError:
  18. # Python3
  19. import tkinter as tk
  20. import tkinter.simpledialog as tksd
  21. import tkinter.messagebox as tkmb
  22.  
  23. def get_data():
  24. # tksd.askfloat(title, prompt [,options])
  25. miles = tksd.askfloat('Miles', 'Enter miles driven')
  26. # give minvalue to avoid division by zero errors
  27. gal = tksd.askfloat('Petrol', 'Enter gallon of petrol consumed',
  28. minvalue=0.1)
  29. str_result = "Your milage is %0.2f miles/gallon" % (miles/gal)
  30. # tkmb.showinfo(title, message [, options])
  31. tkmb.showinfo('Result:', str_result)
  32.  
  33. root = tk.Tk()
  34. str_var = tk.StringVar()
  35.  
  36. tk.Button(root, text="Get data", command=get_data).pack(pady=5)
  37.  
  38. root.mainloop()
Last edited by vegaseat; Nov 22nd, 2009 at 5:11 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 27th, 2009
1
Re: Python GUI Programming
Just testing out some of the many PyQT GUI toolkit widgets:
python Syntax (Toggle Plain Text)
  1. # explore PyQT QLineEdit, QPushButton, QLabel, QMessageBox,
  2. # QHBoxLayout, QWidget, QMainWindow
  3. # tested with Python 3.1.1 and PyQT 4.6.2.2
  4. # ene
  5.  
  6. # easy import
  7. from PyQt4.QtCore import *
  8. from PyQt4.QtGui import *
  9.  
  10. class MyWindow(QMainWindow):
  11. def __init__(self, parent= None):
  12. QMainWindow.__init__(self, parent)
  13. # setGeometry(x_pos, y_pos, width, height)
  14. self.setGeometry(100, 150, 320, 100)
  15. self.setWindowTitle("Explore QLineEdit")
  16. self.create_widgets()
  17.  
  18. def create_widgets(self):
  19. self.label = QLabel("Say hello:")
  20. self.edit = QLineEdit()
  21. self.button = QPushButton("Push Me!")
  22. # connect signal to button
  23. #QObject.connect(self.button, SIGNAL("clicked()"), self.on_click)
  24. # newer connect style used with PyQT 4.5+
  25. self.button.clicked.connect(self.on_click)
  26.  
  27. # use horizontal layout
  28. h_box = QHBoxLayout()
  29. h_box.addWidget(self.label)
  30. h_box.addWidget(self.edit)
  31. h_box.addWidget(self.button)
  32. # create central widget, add layout and set
  33. central_widget = QWidget()
  34. central_widget.setLayout(h_box)
  35. self.setCentralWidget(central_widget)
  36.  
  37. def on_click(self):
  38. """the button has been clicked"""
  39. msg = "Good day %s" % self.edit.displayText()
  40. QMessageBox.information(self, "Title", msg, QMessageBox.Ok)
  41.  
  42.  
  43. # test potential module
  44. if __name__ == "__main__":
  45. app = QApplication([])
  46. window = MyWindow()
  47. window.show()
  48. app.exec_()
Reputation Points: 625
Solved Threads: 211
Posting Virtuoso
Ene Uran is offline Offline
1,704 posts
since Aug 2005
Dec 12th, 2009
0
Re: Python GUI Programming
A Tkinter resizing example that shows two frames on a frame that in this case respond differently to the resizing of the main window ...
python Syntax (Toggle Plain Text)
  1. # experiments with Tkinter resizing
  2. # two frames on a frame, keep one frame height fairly constant
  3. # vegaseat
  4.  
  5. try:
  6. # Python2
  7. import Tkinter as tk
  8. except ImportError:
  9. # Python3
  10. import tkinter as tk
  11.  
  12. class MyApp(tk.Frame):
  13. def __init__(self, master=None):
  14. tk.Frame.__init__(self, master, bg='yellow')
  15. self.prepare_resizing()
  16. # set the title, self.top is from prepare_resizing()
  17. # and is actually the master in this case
  18. self.top.title("Two Frames (resize the window)")
  19. self.make_widgets()
  20.  
  21. def prepare_resizing(self):
  22. """ needed for stretch/resize """
  23. self.grid(sticky='nswe')
  24. self.top = root.winfo_toplevel()
  25. self.top.rowconfigure(0, weight=1)
  26. self.top.columnconfigure(0, weight=1)
  27. # there are two rows in this example
  28. # set row ratios
  29. self.rowconfigure(0, weight=1)
  30. # make weight for row 1 very high to keep row 0 constant
  31. self.rowconfigure(1, weight=1000)
  32. # there is only one column in this example
  33. self.columnconfigure(0, weight=1)
  34.  
  35. def make_widgets(self):
  36. # put frame1 in row 0 to keep it fixed in height
  37. frame1 = tk.Frame(self, bg='brown', width=400, height=50)
  38. frame1.grid(row=0, column=0, sticky='nesw')
  39. # needed for width and height
  40. frame1.grid_propagate(0)
  41. # need for button to stick 'w'
  42. frame1.columnconfigure(0, weight=1)
  43.  
  44. # put frame2 in row 1 to make it resize
  45. frame2 = tk.Frame(self, bg='green', width=400, height=200)
  46. frame2.grid(row=1, column=0, sticky='nesw')
  47. # needed for width and height
  48. frame2.grid_propagate(0)
  49. # need for button to stick 'e'
  50. frame2.columnconfigure(0, weight=1)
  51.  
  52. b1 = tk.Button(frame1, text="Frame1 Button1")
  53. # this grid is inside frame1
  54. b1.grid(row=0, column=0, padx=5, pady=10, sticky='w')
  55.  
  56. b2 = tk.Button(frame2, text="Frame2 Button2")
  57. b2.grid(row=0, column=0, padx=5, pady=10, sticky='e')
  58.  
  59.  
  60. root = tk.Tk()
  61. app = MyApp(master=root)
  62. root.mainloop()
Experiment with the row weight ratios here to see the response. If you have more than one column you can do the same with column weights. The Tkinter syntax is not very intuitive in this case, so study it carefully.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
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