关于Python TKinter动态选择菜单的更多信息
我正在尝试修改这里的代码,让用户确认从optionmenus
中选择的项目。如果用户点击提交按钮,就应该弹出一个消息框来确认。最后,我想把选中的项目作为变量返回给程序,这样可以在其他函数中进一步处理。不过,我的修改没有成功;它只是返回了一个空窗口。你们觉得我缺少了什么呢?非常感谢。
from tkinter import *
import tkinter.messagebox
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.dict = {'Asia': ['Japan', 'China', 'Malasia'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia']}
self.variable_a = StringVar(self)
self.variable_b = StringVar(self)
self.variable_a.trace('w', self.updateoptions)
self.optionmenu_a = OptionMenu(self, self.variable_a, *self.dict.keys())
self.variable_a.set('Asia')
self.optionmenu_a.pack()
self.optionmenu_b = OptionMenu(self, self.variable_b, ())
self.optionmenu_b.pack()
self.btn = Button(self, text="Submit", width=8, command=self.submit)
self.btn.pack()
self.pack()
def updateoptions(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda country=country: self.variable_b.set(country))
def submit(self, *args):
var1 = self.variable_a.get()
var2 = self.variable_b.get()
if tkinter.messagebox.askokcancel("Selection", "Confirm selection: " + var1 + ' ' + var2):
print(var1, var2) #Or can be other function for further processing
root = Tk()
app = App(root)
app.mainloop()
Python版本 3.4.1
编辑:现在窗口里有了控件。我之前在按钮前面漏写了self.
。不过我还是收到了一个错误信息,我正在尝试解决:AttributeError: 'App'对象没有属性'optionmenu_b'
1 个回答
3
这里 @sedeh,按照你的想法,这个是可以正常工作的。错误并不是因为你的插件,而是因为你用了 from tkinter import *
这种写法,而不是 import tkinter as tk
。所以当你运行代码时,tk窗口一出现就报错了。
我做的就是把你给的链接里的代码拿过来,加上你写的部分,这样就没有错误了。
import tkinter as tk
import tkinter.messagebox
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.dict = {'Asia': ['Japan', 'China', 'Malasia'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia']}
self.variable_a = tk.StringVar(self)
self.variable_b = tk.StringVar(self)
self.variable_a.trace('w', self.updateoptions)
self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys())
self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '')
self.variable_a.set('Asia')
self.optionmenu_a.pack()
self.optionmenu_b.pack()
self.btn = tk.Button(self, text="Submit", width=8, command=self.submit)
self.btn.pack()
self.pack()
def updateoptions(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda country=country: self.variable_b.set(country))
def submit(self, *args):
var1 = self.variable_a.get()
var2 = self.variable_b.get()
if tkinter.messagebox.askokcancel("Selection", "Confirm selection: " + var1 + ' ' + var2):
print(var1, var2) #Or can be other function for further processing
root = tk.Tk()
app = App(root)
app.mainloop()
希望这对你有帮助。