Tkinter example code for multiple windows, why won't buttons load correctly?

前端 未结 5 1912
独厮守ぢ
独厮守ぢ 2020-12-02 07:44

I am writing a program which should:

  1. Open a window with the press of a button.
  2. Close the newly opened window with the press of another button.
5条回答
  •  [愿得一人]
    2020-12-02 08:45

    You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

    Quick fix: add the frame new as the first argument to your Button in Demo2.

    Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

    class Demo2(tk.Toplevel):     
        def __init__(self):
            tk.Toplevel.__init__(self)
            self.title("Demo 2")
            self.button = tk.Button(self, text="Button 2", # specified self as master
                                    width=25, command=self.close_window)
            self.button.pack()
    
        def close_window(self):
            self.destroy()
    

    Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

提交回复
热议问题