Jump to content
Wikibooks The Free Textbook Project

Python Programming/Tkinter

From Wikibooks, open books for an open world

Tkinter is a Python wrapper for Tcl/Tk providing a cross-platform GUI toolkit. On Windows, it comes bundled with Python; on other operating systems, it can be installed. The set of available widgets is smaller than in some other toolkits, but since Tkinter widgets are extensible, many of the missing compound widgets can be created using the extensibility, such as combo box and scrolling pane.

IDLE, Python's Integrated Development and Learning Environment, is written using Tkinter and is often distributed with Python. You can learn about features of Tkinter by playing around with menus and dialogs of IDLE. For instance, Options > Configure IDLE... dialog shows a broad variety of GUI elements including tabbed interface. You can learn about programming using Tkinter by studying IDLE source code, which, on Windows, is available e.g. in C:\Program Files\Python27\Lib\idlelib.

Python 3: The examples on this page are for Python 2. In Python 3, what was previously module Tkinter is tkinter, what was tkMessageBox is messagebox, etc.

Minimal example

[edit | edit source ]

A minimal example:

fromTkinterimport *
root = Tk()
frame = Frame(root)
frame.pack()
label = Label(frame, text="Hey there.")
label.pack()
quitButton = Button(frame, text="Quit", command=frame.quit)
quitButton.pack()
root.mainloop()

A minimal example made more compact - later references to GUI items not required:

fromTkinterimport *
root = Tk()
frame = Frame(root)
frame.pack()
Label(frame, text="Hey there.").pack()
Button(frame, text="Quit", command=frame.quit).pack()
root.mainloop()

A minimal example creating an application class derived from Frame:

fromTkinterimport *
classApp(Frame):
 def__init__(self, master):
 Frame.__init__(self)
 self.label = Label(master, text="Hey there.")
 self.label.pack() 
 self.quitButton = Button(master, text="Quit", command=self.quit)
 self.quitButton.pack()
if __name__ == '__main__':
 root = Tk()
 app = App(root)
 root.mainloop()

Message boxes

[edit | edit source ]

Simple message boxes can be created using tkMessageBox as follows:

importTkinter,tkMessageBox
Tkinter.Tk().withdraw() # Workaround: Hide the window
answer = tkMessageBox.askokcancel("Confirmation", "File not saved. Discard?")
answer = tkMessageBox.askyesno("Confirmation", "Do you really want to delete the file?")
# Above, "OK" and "Yes" yield True, and "Cancel" and "No" yield False
tkMessageBox.showwarning("Warning", "Timeout has elapsed.")
tkMessageBox.showwarning("Warning", "Timeout has elapsed.", icon=tkMessageBox.ERROR)
tkMessageBox.showerror("Warning", "Timeout has elapsed.")

Links:

File dialog

[edit | edit source ]

File dialogs can be created as follows:

importTkinter,tkFileDialog
Tkinter.Tk().withdraw() # Workaround: Hide the window
filename1 = tkFileDialog.askopenfilename()
filename2 = tkFileDialog.askopenfilename(initialdir=r"C:\Users")
filename3 = tkFileDialog.asksaveasfilename()
filename4 = tkFileDialog.asksaveasfilename(initialdir=r"C:\Users")
if filename1 <> "":
 for line in open(filename1): # Dummy reading of the file
 dummy = line.rstrip()

Links:

Radio button

[edit | edit source ]

A radio button can be used to create a simple choice dialog with multiple options:

fromTkinterimport *
master = Tk() 
choices = [("Apple", "a"), ("Orange", "o"), ("Pear", "p")]
defaultChoice = "a"
userchoice = StringVar()
userchoice.set(defaultChoice)
defcancelAction(): userchoice.set("");master.quit()
 Label(master, text="Choose a fruit:").pack()
for text, key in choices: 
 Radiobutton(master, text=text, variable=userchoice, value=key).pack(anchor=W)
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if userchoice.get() <>"":
 print userchoice.get() # "a", or "o", or "p"
else:
 print "Choice canceled."

An alternative to radio button that immediately reacts to button press:

fromTkinterimport *
importos
buttons = [("Users", r"C:\Users"),
 ("Windows", r"C:\Windows"),
 ("Program Files", r"C:\Program Files")]
master = Tk()
defopen(filePath):
 defopenInner():
 os.chdir(filePath) # Cross platform
 #os.system('start "" "'+filePath+'') # Windows
 master.quit()
 return openInner
Label(master, text="Choose a fruit:").pack()
for buttonLabel, filePath in buttons:
 Button(master, text=buttonLabel, command=open(filePath)).pack(anchor=W)
mainloop()

Links:

List box

[edit | edit source ]

A list box can be used to create a simple multiple-choice dialog:

fromTkinterimport *
master = Tk() 
choices = ["Apple", "Orange", "Pear"]
canceled = BooleanVar()
defcancelAction(): canceled.set(True); master.quit()
Label(master, text="Choose a fruit:").pack()
listbox = Listbox(master, selectmode=EXTENDED) # Multiple options can be chosen
for text in choices: 
 listbox.insert(END, text)
listbox.pack() 
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if not canceled.get():
 print listbox.curselection() # A tuple of choice indices starting with 0
 # The above is a tuple even if selectmode=SINGLE
 if "0" in listbox.curselection(): print "Apple chosen."
 if "1" in listbox.curselection(): print "Orange chosen."
 if "2" in listbox.curselection(): print "Pear chosen." 
else:
 print "Choice canceled."

Links:

Checkbox

[edit | edit source ]

Checkbox or check button can be created as follows:

fromTkinterimport *
root = Tk()
checkbuttonState = IntVar()
Checkbutton(root, text="Recursive", variable=checkbuttonState).pack()
mainloop()
print checkbuttonState.get() # 1 = checked; 0 = unchecked

Links:

Entry

[edit | edit source ]

Entry widget, a single-line text input field, can be used as follows:

fromTkinterimport *
root = Tk()
Label(text="Enter your first name:").pack()
entryContent = StringVar()
Entry(root, textvariable=entryContent).pack()
mainloop()
print entryContent.get()

Links:

[edit | edit source ]

Menus can be created as follows:

fromTkinterimport *
root = Tk()
defmycommand(): print "Chosen."
menubar = Menu(root)
menu1 = Menu(menubar, tearoff=0)
menu1.add_command(label="New", command=mycommand)
menu1.add_command(label="Clone", command=mycommand)
menu1.add_separator()
menu1.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Project", menu=menu1)
 
menu2 = Menu(menubar, tearoff=0)
menu2.add_command(label="Oval", command=mycommand)
menu2.add_command(label="Rectangle", command=mycommand)
menubar.add_cascade(label="Shapes", menu=menu2)
root.config(menu=menubar)
mainloop()

Links:

LabelFrame

[edit | edit source ]

A frame around other elements can be created using LabelFrame widget as follows:

fromTkinterimport *
root = Tk()
Label(text="Bus").pack()
frame = LabelFrame(root, text="Fruits") # text is optional
frame.pack()
Label(frame, text="Apple").pack()
Label(frame, text="Orange").pack()
mainloop()

Links:

Message

[edit | edit source ]

Message is like Label but ready to wrap across multiple lines. An example:

fromTkinterimport *
root = Tk()
Message(text="Lazy brown fox jumped. " * 5, width=100).pack() # width is optional
mainloop()

Links:

Option menu

[edit | edit source ]

Drop-down list, in Tkinter option menu, can be created as follows:

fromTkinterimport *
root = Tk()
options = ["Apple", "Orange", "Pear"]
selectedOption = StringVar()
selectedOption.set("Apple") # Default
OptionMenu(root, selectedOption, *options).pack() 
mainloop()
print selectedOption.get() # The text in the options list

Links:

Text

[edit | edit source ]

Text widget is a more complex one, allowing editing of both plain and formatted text, including multiple fonts.

Example to be added.

Links:

Tcl/Tk version

[edit | edit source ]

The Windows installer for Python 2.3 ships with Tcl/Tk 8.4.3. You can find out about the version:

importTkinter
print Tkinter.TclVersion # Up to 8.5
print Tkinter.TkVersion # Up to 8.5

Links:

[edit | edit source ]
[edit | edit source ]

AltStyle によって変換されたページ (->オリジナル) /