tkinter动态OptionMenu命令不起作用

时间:2015-04-10 12:47:59

标签: python tkinter optionmenu

我正在使用python 2.7.9而我当前的问题是由于某种原因,我的OptionMenu命令无效。以下是我的意思的示例代码。

from Tkinter import *

root = Tk()
var = StringVar()
var.set("Choose a name...")
names = []

# Appends names to names list and updates OptionMenu
def createName(n):
    names.append(n)
    personName.delete(0, "end")
    menu = nameMenu['menu']
    menu.delete(0, "end")
    for name in names:
        menu.add_command(label=name, command=lambda name=name: var.set(name))

# what to run when a name is selected
def selection():
    print "Running"  # For testing purposes to see when/if selection runs
    print var.get()

# Option Menu for names
nameMenu = OptionMenu(root, var, (), command=lambda: selection())
nameMenu.grid(row=0, column=0, columnspan=2)
nameMenu.config(width=20)

# Entry for user to submit name
Label(root, text="Name").grid(row=1, column=0)
personName = Entry(root, width=17)
personName.grid(row=1, column=1)

# Add person Button
Button(root, text="Add Person", width=20, command=
       lambda: createName(personName.get())).grid(row=5, column=0, columnspan=2)

mainloop()

此理论程序的目的只是为OptionMenu添加名称,然后当您选择名称时,它将打印它。我可以为OptionMenu添加名称,但是当OptionMenu运行selection()函数时,它就不会。

现在我最好的猜测是什么错误只是按钮调用的createName()函数也使用了OptionMenu的命令,因为行

menu.add_command(label=name, command=lambda name=name: var.set(name))

这周围有吗? OptionMenu可能有多个命令吗?

1 个答案:

答案 0 :(得分:2)

您正走在正确的轨道上......但是您可以将名称传递给selection()函数,而不是更改StringVar:

from Tkinter import *

root = Tk()

var = StringVar()
var.set("Choose a name...")
names = []

# Appends names to names list and updates OptionMenu
def createName(n):
    names.append(n)
    personName.delete(0, "end")
    menu = nameMenu['menu']
    menu.delete(0, "end")
    for name in names:
        menu.add_command(label=name, command=lambda name=name: selection(name))

# what to run when a name is selected
def selection(name):
    var.set(name)
    print "Running"  # For testing purposes to see when/if selection runs
    print name

# Option Menu for names
nameMenu = OptionMenu(root, var, ())
nameMenu.grid(row=0, column=0, columnspan=2)
nameMenu.config(width=20)

# Entry for user to submit name
Label(root, text="Name").grid(row=1, column=0)
personName = Entry(root, width=17)
personName.grid(row=1, column=1)


# Add person Button
Button(root, text="Add Person", width= 20, command=lambda: createName(personName.get())).grid(row=5, column=0, columnspan=2)


mainloop()