Skip to content Skip to sidebar Skip to footer

New Instance Of Toplevel Classes Make Overlapping Widgets

I'm generally new to python and tkinter. I've been programming maybe about a year or so, and I've just started to try to make each tkinter toplevel window its own class because I'v

Solution 1:

You are calling class MainWindow: every time you press the New Button. This is remaking all the widgets over and over. And they way you are creating the MainWindow is affecting how you can interact with MainWindow.

Change:

def main():
    root = Tk()
    MainWindow(root)
    root.mainloop()

if __name__ == "__main__":
    main()

To:

 if __name__ == "__main__":
    root = Tk()
    main = MainWindow(root)
    root.mainloop()

Once you have made this change you are able to interact with the instance attributes and methods of main

Below is a modified version of your code. You will notice when you press the button I added to the TopLevel window it will print information from an atribute and method of main variable. It will also place some text in the entry box in the MainWindow.

from tkinter import *
from tkinter import ttk

classMainWindow:
    def__init__(self, master):
        self.master = master
        self.btn = ttk.Button(self.master, text="New", command=self.item_input_show)
        self.btn.pack(side = TOP)
        self.entry = Entry(self.master)
        self.entry.pack(side = BOTTOM)
        self.numbers = 200deftwo_plus_x(self, x):
        math = 2 + x
        return math

    defitem_input_show(self):
        ItemInput(self.master)


classItemInput:
    def__init__(self, master):
        self.master = master
        self.topItemInput = Toplevel(master)
        self.btn = ttk.Button(self.topItemInput, text="Use method in MainWindow", command = self.do_something_from_main)
        self.btn.pack()

    defdo_something_from_main(self):
        print(main.numbers)
        print(main.two_plus_x(10))
        main.entry.delete(0, END)
        main.entry.insert(0, "From ItemInput Class")

# notice I removed def main(): as it was preventing us from interacting with the main variable.if __name__ == "__main__":
    root = Tk()
    main = MainWindow(root)
    root.mainloop()

Post a Comment for "New Instance Of Toplevel Classes Make Overlapping Widgets"