选择OptionMenu选项时如何显示小部件?

时间:2015-10-26 23:04:01

标签: python-3.x tkinter

我有一个OptionMenu,我希望当选择其中一个选项时,会显示一个小部件。

例如

...
var = StringVar()

w = OptionMenu(root, var, "apple", "orange", "grapes")
w.grid(column=1, row=1)
w.config(width=15)

var.set(" ")

现在,如果我选择"apple",那么它应该显示标签或按钮,说“苹果是红色的”。

1 个答案:

答案 0 :(得分:2)

我认为这可能是你之后的

import tkinter as tk

def toggle(item):
    #Destorys all existing widgets in frame
    for wid in wid_frame.winfo_children():
        wid.destroy()

    #Packs the selected widget
    if item == 'Label':
        tk.Label(wid_frame, text='Hello World!').pack()

    elif item == 'Button':
        tk.Button(wid_frame, text='Hello World!').pack()

    elif item == 'Entry':
        tk.Entry(wid_frame).pack()

root = tk.Tk()

var = tk.StringVar()
var.set("Pick Widget")

op_menu = tk.OptionMenu(root, var, "None", "Label", "Button", "Entry", command=toggle)
op_menu.pack()
op_menu.config(width=15)

wid_frame = tk.Frame(root)
wid_frame.pack()

root.mainloop()