Python 条目小部件元组组合
我一直在尝试把输入框和元组结合起来,用的是Python 2.7的tkinter库。通过这段代码,我应该可以输入一个水果的名字,然后在水果元组里查找这个水果。如果找到了,就用一组单选按钮显示这个水果的特点。
from Tkinter import*
class Fruit:
def __init__(self, parent):
# variables
self.texture_option = StringVar()
self.climate_option = StringVar()
# layout
self.myParent = parent
self.main_frame = Frame(parent, background="light blue")
self.main_frame.pack(expand=YES, fill=BOTH)
texture_options = ["Soft", "Crunchy","?"]
climate_options = ["Temperate", "Tropical","?"]
self.texture_option.set("?")
self.climate_option.set("?")
self.texture_options_frame = Frame(self.main_frame, borderwidth=3, background="light blue")
self.texture_options_frame.pack(side=TOP, expand=YES, anchor=W)
Label(self.texture_options_frame, text="Texture:", relief=FLAT, font="bold", background="light blue").pack(side=LEFT,anchor=W)
for option in texture_options:
button = Radiobutton(self.texture_options_frame, text=str(option), indicatoron=0,
value=option, padx=5, variable=self.texture_option, background="light blue")
button.pack(side=LEFT)
self.climate_options_frame = Frame(self.main_frame, borderwidth=3, background="light blue")
self.climate_options_frame.pack(side=TOP, expand=YES, anchor=W)
Label(self.climate_options_frame, text="Climate:", relief=FLAT, font="bold", background="light blue").pack(side=LEFT,anchor=W)
for option in climate_options:
button = Radiobutton(self.climate_options_frame, text=str(option), indicatoron=0,
value=option, padx=5, variable=self.climate_option, background="light blue")
button.pack(side=LEFT)
#search button
self.search_frame = Frame(self.main_frame, borderwidth=5, height=50, background="light blue")
self.search_frame.pack(expand=NO)
enter = Entry(self.search_frame, width=30).pack(side=LEFT, expand=NO, padx=5, pady=5, ipadx=5, ipady=5)
self.searchbutton = Button(self.search_frame, text="Search", foreground="white", background="blue",
width=6, padx="2m", pady="1m")
self.searchbutton.pack(side=LEFT, pady=5)
self.searchbutton.bind("<Button-1>", self.searchbuttonclick)
self.searchbutton.bind("<Return>", self.searchbuttonclick)
def searchbuttonclick(self,event):
#fruit texture climate
fruit_bowl=[
('Apple', 'Crunchy','Temperate'),
('Orange', 'Soft','Tropical'),
('Pawpaw','Soft','Temperate')]
if enter.get()==fruit_bowl[x][0]:
self.texture_option.set()==fruit_bowl[x][1]
self.climate_option.set()==fruit_bowl[x][2]
root = Tk()
root.title("Fruit Bowl")
fruit = Fruit(root)
root.mainloop()
但是我遇到了一个错误提示,显示“名称错误:全局名称'enter'未定义”。有没有人知道为什么这个代码不工作呢?
1 个回答
2
问题在于,你在一个方法里定义了“enter”这个变量,但在另一个方法里想要使用它。因为在那个方法里没有这个变量,所以Python就会去找全局变量,但找不到,于是就报错了。
解决这个问题很简单:只需要把“enter”变量变成你“Fruit”类的一个属性。在使用这个变量的地方前面加上self.
,这样它就可以在你这个对象的所有方法里使用了。
具体来说,把这一行:
enter = Entry(self.search_frame, width=30).pack(side=LEFT, expand=NO, padx=5, pady=5, ipadx=5, ipady=5)
改成:
self.enter = Entry(self.search_frame, width=30).pack(side=LEFT, expand=NO, padx=5, pady=5, ipadx=5, ipady=5)
然后把这行:
if enter.get()==fruit_bowl[x][0]:
改成:
if self.enter.get()==fruit_bowl[x][0]: