保存OptionMenu输入-tkinter

时间:2018-07-31 11:06:03

标签: python tkinter

我从互联网上改编了一个简单的示例,以创建一个简单的下拉菜单。我正在尝试用户的输入,以便在他们关闭输入框后就可以使用它。我的最新尝试如下所示:

from tkinter import *

root = Tk()
root.title("Tk dropdown example")

# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)

# Create a Tkinter variable
tkvar1 = StringVar(root)
tkvar2 = StringVar(root)

choices_wl = [2,3,4]

popupMenu = OptionMenu(mainframe, tkvar1, *choices_wl)
Label(mainframe, text="Select a number").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)

choices_rw = [5,10,15,20]


popupMenu = OptionMenu(mainframe, tkvar2, *choices_rw)
Label(mainframe, text="Select a width").grid(row = 1, column = 2)
popupMenu.grid(row = 2, column =2)

quit_button = Button(mainframe, text="OK", command=root.destroy).grid(row = 5, column = 2)

# on change dropdown value
def change_dropdown1(*args):
    number=tkvar1.get()
    tkvar1.set(number)
    return number

def change_dropdown2(*args):
    print( tkvar2.get() )

# link function to change dropdown
tkvar1.trace('w', change_dropdown1)
number = change_dropdown1()
tkvar2.trace('w', change_dropdown2)

root.mainloop()

print("number=%s" % number)

这不起作用,并且所有打印的内容都是'number ='

任何建议将不胜感激

1 个答案:

答案 0 :(得分:0)

我认为您使事情变得太复杂了。您的tkvar变量会自动跟踪所有变量,因此您只需在mainloop结束后打印每个tkvar的值即可。

删除了2个功能,仅使用了tkvars。

from tkinter import *

root = Tk()
root.title("Tk dropdown example")

mainframe = Frame(root)
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)

tkvar1 = StringVar(root)
tkvar2 = StringVar(root)

choices_wl = [2, 3, 4]
choices_rw = [5, 10, 15, 20]

popupMenu = OptionMenu(mainframe, tkvar1, *choices_wl)
Label(mainframe, text="Select a number").grid(row=1, column=1)
popupMenu.grid(row=2, column=1)

popupMenu = OptionMenu(mainframe, tkvar2, *choices_rw)
Label(mainframe, text="Select a width").grid(row=1, column=2)
popupMenu.grid(row=2, column=2)

quit_button = Button(mainframe, text="OK", command=root.destroy).grid(row=5, column=2)

root.mainloop()

# this line works fine on my end.
print("numbers = {}, {}".format(tkvar1.get(), tkvar2.get()))

尽管我觉得这个打印语句不应该工作,因为我们销毁了tkinter实例,我以为那也应该销毁tkvar的实例,但我想不是。也许有人可以帮我了解一下。