[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

options; clicking on the third “state” button fetches and prints the current values dis-
played in the first two.


Example 9-7. PP4E\Gui\Tour\optionmenu.py


from tkinter import *
root = Tk()


var1 = StringVar()
var2 = StringVar()
opt1 = OptionMenu(root, var1, 'spam', 'eggs', 'toast') # like Menubutton
opt2 = OptionMenu(root, var2, 'ham', 'bacon', 'sausage') # but shows choice
opt1.pack(fill=X)
opt2.pack(fill=X)
var1.set('spam')
var2.set('ham')


def state(): print(var1.get(), var2.get()) # linked variables
Button(root, command=state, text='state').pack()
root.mainloop()


Figure 9-9. An Optionmenu at work


There are other menu-related topics that we’ll skip here in the interest of space. For
instance, scripts can add entries to system menus and can generate pop-up menus
(posted in response to events, without an associated button). Refer to Tk and tkinter
resources for more details on this front.


Figure 9-8. A Menubutton all by itself


516 | Chapter 9: A tkinter Tour, Part 2

Free download pdf