简体   繁体   中英

Python TkInter bind breaking

I have a simple GUI which uses key binds - something like this.

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()

Now, this works just fine when load_config() finds what it was looking for. I can use the binds and even after using '9' and loading new config, everything works.
Problem is, if load_config() fails, self.conf gets set to None and load_new_conf gets called from __init__ , the binds are no longer operational.

I figured out that the problem is caused by tkFileDialog.askopenfilename() being called from within __init__ . What I don't understand is why this happens and how to get around it.

This code works for me:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM