我有一个使用键绑定的简单GUI - 就像这样。
import Tkinter, tkFileDialog
class Foo(object):
def __init__(self, master):
master.bind('3', self.do_bar)
master.bind('9', self.load_new_config)
self.load_config()
if not self.conf:
self.load_new_config()
else:
self.load_data()
def load_config(self):
try:
self.conf = #get stuff from known file
except FailedToGetStuff:
self.conf = None
def load_new_config(self):
path = askopenfilename(initialdir='~')
self.conf = #get stuff from file in path
self.load_data()
def load_data(self):
#get data from self.conf, process and display
def do_bar(self):
#do stuff with displayed data
if __name__ == "__main__"
root = Tk()
Foo(root)
root.mainloop()
现在,当load_config()找到它要查找的内容时,这很好用。我可以使用绑定,甚至在使用'9'并加载新配置后,一切正常
问题是,如果load_config()失败,self.conf将设置为None并且从__init__
调用load_new_conf,则绑定将不再可用。
我发现问题是由__init__
内的tkFileDialog.askopenfilename()引起的。我不明白为什么会发生这种情况以及如何解决这个问题。
答案 0 :(得分:0)
此代码适用于我:
import Tkinter, tkFileDialog
class Foo(object):
def __init__(self, master):
master.bind('<KeyPress-3>', self.do_bar)
master.bind('<KeyPress-9>', self.load_new_config)
self.load_config()
if not self.conf:
master.after(1, self.load_new_config)
else:
self.load_data()
def load_config(self):
try:
self.conf = None#get stuff from known file
except FailedToGetStuff:
self.conf = None
def load_new_config(self, e = 0):
path = tkFileDialog.askopenfilename(initialdir='~')
self.conf = None#get stuff from file in path
self.load_data()
def load_data(self, e = 0):
pass
#get data from self.conf, process and display
def do_bar(self, e = 0):
print 1
#do stuff with displayed data
if __name__ == "__main__":
root = Tkinter.Tk()
Foo(root)
root.mainloop()