| | |
Python GUI Programming
![]() |
2
#71 Oct 13th, 2009
Creating a simple shadow effect around a Tkinter frame ...
python Syntax (Toggle Plain Text)
# create a frame with a shadow effect border # using overlapping frames # vegaseat try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() w = 320 h = 220 x = 150 y = 100 # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (w, h, x, y)) root.title("shadow effect border") frame1 = tk.Frame(root, bg='grey', width=w-30, height=h-30) frame1.place(x=20, y=20) frame2 = tk.Frame(root, bg='yellow', width=w-30, height=h-30) frame2.place(x=10, y=10) root.mainloop()
May 'the Google' be with you!
2
#72 Oct 14th, 2009
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)
# show width and height of Tkinter's root window # vegaseat try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() w = 460 h = 320 x = 150 y = 100 # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # update is needed root.update() geo = root.geometry() print(geo) # 460x320+150+100 width = root.winfo_width() # 460 print(width) height = root.winfo_height() # 320 print(height) root.mainloop()
Last edited by vegaseat; Oct 14th, 2009 at 5:18 pm.
May 'the Google' be with you!
1
#73 Oct 14th, 2009
Here is typical code that I use with the py2exe module to convert Tkinter programs to an executable package for Windows computers ...
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.
python Syntax (Toggle Plain Text)
""" Simple py2exe version used for Tkinter programs. Run this program to create a windows exe file with py2exe. Run it in a folder that als contains your source code file. It will create 2 folders named build and dist. The build folder is temporary info and can be deleted. Distribute whatever is in the dist folder. Your library.zip file contains your optimized byte code, and all needed modules. This file together with the Python interpreter (eg. Python25.dll) should accompany the created executable file. Note that you might be able to share this large library file with other Python/Tkinter based .exe files. The MSVCR71.dll can be distributed and is often already in the Windows/system32 folder. w9xpopen.exe is needed for os.popen() only, can be deleted otherwise. """ from distutils.core import setup import py2exe import sys sys.argv.append("py2exe") sys.argv.append("-q") # insert your own source code filename below ... code_file = 'Tk_ParResist1.pyw' # replace windows with console for a console program setup(windows = [{"script": code_file}])
Last edited by vegaseat; Oct 14th, 2009 at 5:54 pm.
May 'the Google' be with you!
2
#74 Oct 23rd, 2009
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)
# show a colorful splash message for a set time then quit # tested with PyQT45 by vegaseat from PyQt4.QtCore import * from PyQt4.QtGui import * def do_html(text, color='black', size=3): """create a line of html code for text with color and size""" sf = "<FONT color=%s size=%d>%s</FONT>" return sf % (color, size, text) # build up simple HTML code ... # text between <B> and </B> is bold # <BR> inserts a line break (new line) html = "" html += '<BR>' orange = "#FFBA00" # gives a better orange color color_list = ['red', orange, 'yellow', 'green', 'blue'] ix = 0 for c in 'WE LOVE RAINBOWS': # make character c bold c = "<B>" + c + "</B>" if ix >= len(color_list): ix = 0 html += do_html(c, color_list[ix], 7) ix += 1 html += '<BR>' # create a QT GUI application app = QApplication([]) label = QLabel(html) # show label without frame # comment line out if you want a frame label.setWindowFlags(Qt.SplashScreen) label.show() # show for x milliseconds, then quit x = 5000 QTimer.singleShot(x, app.quit) app.exec_()
May 'the Google' be with you!
2
#75 27 Days Ago
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)
# explore Tkinter's Text widget # get the line and column values of the text insertion point # vegaseat import Tkinter as tk def get_position(event): """get the line and column number of the text insertion point""" line, column = text.index('insert').split('.') s = "line=%s column=%s" % (line, column) root.title(s) root= tk.Tk() root.title('start typing') text = tk.Text(root, width=40, height=10) text.bind("<KeyRelease>", get_position) text.pack() # start cursor in text area text.focus() root.mainloop()
May 'the Google' be with you!
0
#76 7 Days Ago
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:
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.
python Syntax (Toggle Plain Text)
# use pygame to bounce/move loaded image around the screen import sys, pygame pygame.init() size = width, height = 320, 240 # this determines the move direction/speed in pixels # speed[0] left or right # speed[1] up or down speed = [2, 2] # color uses r, g, b tuple black = 0, 0, 0 # white works better here white = 255, 255, 255 # create the window screen = pygame.display.set_mode(size) # give the window a title pygame.display.set_caption("watch the beach ball bounce") # make sure the image file is in the working directory # or give full path name ball = pygame.image.load("ball.bmp") # create rectangle object you can move # it is used to put the image on ballrect = ball.get_rect() while True: for event in pygame.event.get(): # window corner x will exit if event.type == pygame.QUIT: sys.exit() # move the rectangle object ballrect = ballrect.move(speed) # change direction if left or right boundry is reached if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] # change direction if top or bottom boundry is reached if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] # clear the screen with white background screen.fill(white) # put the image on the rectangle object screen.blit(ball, ballrect) # update screen pygame.display.flip() # small time delay milliseconds = 20 pygame.time.delay(milliseconds)
Last edited by bumsfeld; 7 Days Ago at 4:45 pm. Reason: IDE
Should you find Irony, you can keep her!
0
#77 4 Days Ago
A simple way to add color highlighted text to the Tkinter Text() widget ...
python Syntax (Toggle Plain Text)
# multiple color text with Tkinter using widget Text() and tags # vegaseat try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk def color_text(edit, tag, word, fg_color='black', bg_color='white'): # add a space to the end of the word word = word + " " edit.insert('end', word) end_index = edit.index('end') begin_index = "%s-%sc" % (end_index, len(word) + 1) edit.tag_add(tag, begin_index, end_index) edit.tag_config(tag, foreground=fg_color, background=bg_color) root = tk.Tk() root.geometry("600x200") edit = tk.Text(root) edit.pack() text = "Up the hill went Jack and Jill, down fell Jill and cried!" # create a list of single words word_list = text.split() #print( word_list ) # test # pick word to be colored myword1 = 'Jack' myword2 = 'Jill' # create a list of unique tags tags = ["tg" + str(k) for k in range(len(word_list))] for ix, word in enumerate(word_list): # word[:len(myword)] for word ending with a punctuation mark if word[:len(myword1)] == myword1: color_text(edit, tags[ix], word, 'blue') elif word[:len(myword2)] == myword2: color_text(edit, tags[ix], word, 'red', 'yellow') else: color_text(edit, tags[ix], word) root.mainloop()
May 'the Google' be with you!
0
#78 4 Days Ago
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)
# use Tkinter popup dialogs for input and output # see: # http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/ # TkIntro/introduction/intro08.htm # simple dialogs are: # askfloat, askinteger, and askstring # messagebox dialogs are: # showinfo, showwarning, showerror, askquestion, askokcancel, # askyesno, askretrycancel # vegaseat try: # Python2 import Tkinter as tk import tkSimpleDialog as tksd import tktkMessageBox as tkmb except ImportError: # Python3 import tkinter as tk import tkinter.simpledialog as tksd import tkinter.messagebox as tkmb def get_data(): # tksd.askfloat(title, prompt [,options]) miles = tksd.askfloat('Miles', 'Enter miles driven') # give minvalue to avoid division by zero errors gal = tksd.askfloat('Petrol', 'Enter gallon of petrol consumed', minvalue=0.1) str_result = "Your milage is %0.2f miles/gallon" % (miles/gal) # tkmb.showinfo(title, message [, options]) tkmb.showinfo('Result:', str_result) root = tk.Tk() str_var = tk.StringVar() tk.Button(root, text="Get data", command=get_data).pack(pady=5) root.mainloop()
Last edited by vegaseat; 4 Days Ago at 5:11 pm.
May 'the Google' be with you!
![]() |
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: Is there a function built-in into python for email?
- Next Thread: Help with printing offsets
| Thread Tools | Search this Thread |
6 abrupt address advanced aliased apax applicaions automation avogadro backend beginner c++ calculator calling code convert coordinates corners curves database development dragging edit embedded error examples excel file forms function google gui hints homework http iframe images infosec input ip jaunty java keyboard keyword launcher leftmouse linux list lists loan loop microsoft movingimageswithpygame newb obexftp output problem programming projects py2exe pygame pygtk pyopengl python random redirect rubyconf samples script server silverlight slicenotation sprite sqlite ssh stop string sum swing table threading tkinter tlapse toolbar tricks tutorial ubuntu ui urllib urllib2 variable ventrilo wikipedia windows wordgame write wxpython xlwt xui xwnidow







