我知道这个主题不是新的,但我找不到用它来使用字典的方法!
问题是,如果我在ComboBox中没有进行选择的情况下进行调用,则会产生NameError。我想我不能“尝试,除了”因为它在函数“cbx_fatura_arama”中。
这是我的代码:
from tkinter import *
from tkinter import ttk
LframeAra = Tk()
class NewCBox(ttk.Combobox):
def __init__(self, master, dictionary, *args, **kw):
ttk.Combobox.__init__(self, master, values = sorted(list(dictionary.keys())), state = 'readonly', *args, **kw)
self.dictionary = dictionary
self.bind('<<ComboboxSelected>>', self.selected) #purely for testing purposes
def value(self):
return self.dictionary[self.get()]
def selected(self, event): #Just to test
global cbx_fatura_arama
cbx_fatura_arama = self.value()
lookup = {'Firma' : 'firma', 'Fatura No' : 'fatura_no', 'Ürün Türü' : 'urun_turu', 'Model No' : 'model_no'}
newcb = NewCBox(LframeAra, lookup)
newcb.grid(row=1, column=7, padx=4, pady=4, sticky='we')
ara_ft = ttk.Entry(LframeAra)
ara_ft.grid(row=1, column=8, padx=4, pady=4, sticky='we')
ara_ft_button = ttk.Button(LframeAra, text="Ara", command=lambda : fatura_ara(cbx_fatura_arama, ara_ft))
ara_ft_button.grid(row=1, column=9, padx=4, pady=4, sticky='we')
def fatura_ara(search, find):
print("Some codes.........", search, find.get() )
mainloop()
我需要的是防止ComboBox在进行选择时出错。或者可以做出默认选择。
你能建议一种方法吗? 提前谢谢。
答案 0 :(得分:2)
这是因为您没有初始化全局变量。你为什么还要使用全局变量?根据需要简单地获取值会更好,而不是每次更改都更新变量。例如:
from tkinter import *
from tkinter import ttk
LframeAra = Tk()
class NewCBox(ttk.Combobox):
def __init__(self, master, dictionary, *args, **kw):
ttk.Combobox.__init__(self, master, values = sorted(list(dictionary.keys())), state = 'readonly', *args, **kw)
self.current(0) # select the first option
self.dictionary = dictionary
def get(self):
return self.dictionary[super().get()]
def fatura_ara():
print("Some codes.........", newcb.get(), ara_ft.get())
lookup = {'Firma' : 'firma', 'Fatura No' : 'fatura_no', 'Ürün Türü' : 'urun_turu', 'Model No' : 'model_no'}
newcb = NewCBox(LframeAra, lookup)
newcb.grid(row=1, column=7, padx=4, pady=4, sticky='we')
ara_ft = ttk.Entry(LframeAra)
ara_ft.grid(row=1, column=8, padx=4, pady=4, sticky='we')
ara_ft_button = ttk.Button(LframeAra, text="Ara", command=fatura_ara)
ara_ft_button.grid(row=1, column=9, padx=4, pady=4, sticky='we')
mainloop()