Tkinter unintentional recursion with menu bar command…cause?

后端 未结 1 823
北海茫月
北海茫月 2021-01-22 03:50

I\'m trying to make a Python GUI using tkinter, and I need a menu item that opens another copy of the main window. I tried to do the following code, and when I ran

相关标签:
1条回答
  • 2021-01-22 04:15

    The problem is in this line:

        file.add_command(label = 'New', command = doathing())
    

    Here, you execute the doathing callback and then try to bind its result (which is None) to the command. In this specific case, this also leads to an infinite recursion, as the callback will create a new instance of the frame, which will again execute the callback, which will create another frame, and so on. Instead of calling the function, you have to bind the function itself to the command.

        file.add_command(label = 'New', command = doathing)  # no ()
    

    In case you need to pass parameters to that function (not the case here) you can use a lambda:

        file.add_command(label = 'New', command = lambda: doathing(params))
    

    Also, instead of creating another Tk instance you should probably just create a Toplevel instance in the callback, i.e.

    def doathing():
        thing1 = tk.Toplevel()
        thing2 = TheThing(thing1)
    
    0 讨论(0)
提交回复
热议问题