0

Suppose I have two tkinter classes which act as separate windows. How could I edit any given widget from one class in the other tkinter class. ALso, how could I add a widget in one tkinter class from the other tkinter class?

from tkinter import Tk, Label, Button

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is 
        our first GUI!")
        self.label.pack()

        self.greet_button = Button(master, 
        text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, 
        text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

from tkinter import Tk, Label, Button

class MyFirstGUI2:
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is 
        our first GUI!")
        self.label.pack()

        self.greet_button = Button(master, 
        text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, 
        text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

root = Tk()
my_gui = MyFirstGUI2(root)
root.mainloop()
  • 2
    Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) and [Tkinter understanding mainloop](https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop) – stovfl Jan 08 '20 at 20:41

1 Answers1

0

I think it would be better to use a Toplevel widget for your two windows (or at least one of them). Right now your first window will be created and the code will stop when it gets to the root.mainloop() line. The second window will not be created until you close the first one.

And you can pass in a reference from each class.

import tkinter
from tkinter import Tk, Label, Toplevel, Button

class MainWidget:
    def __init__(self, master):
        self.master = master
        self.widgetTwo = None

        self.label = Label(self.master, text='Widget One')
        self.label.pack()

class WidgetTwo(Toplevel):
    def __init__(self, master, mainWidget):
        Toplevel.__init__(self, master)
        self.master = master
        self.mainWidget = mainWidget

        self.labelTwo = Label(self, text='Widget Two')
        self.labelTwo.pack()

        Button(self, text='Change Main Widget Text', command=self.ChangeMainWidgetLabel).pack()

    def ChangeMainWidgetLabel(self):
        self.mainWidget.label.config(text='Widget One text changed')


mw = Tk()

mainWidget = MainWidget(mw)
widgetTwo = WidgetTwo(mw, mainWidget)
mainWidget.widgetTwo = widgetTwo

mw.mainloop()
Dave1551
  • 323
  • 2
  • 13