In Tkinter, how can I execute a function in a subwindow (Toplevel window) from the main window? In the code below, after I click the sayHelloInNewWindow button from the main window, I expected it to print a label that say Hello in a new window.
import ttkbootstrap as tb
import tkinter as tk
class Main():
def __init__(self, window):
# Window
window.title("Main") # Set the window title
window.geometry("480x720") # Set window size
createWindowButton = tb.Button(window, text="Create a window", command=self.new_window)
createWindowButton.pack(side="top")
sayHelloInNewWindow = tb.Button(window, text="Say Hello in New Window", command=self.newtab.sayhello)
sayHelloInNewWindow.pack(side="bottom")
def new_window(self):
self.newtab = NewWindow(tk.Toplevel(window))
class NewWindow():
def __init__(self, window):
window.title("New Window")
window.geometry("480x720") # Set window size
def sayhello(self):
helloLabel = tb.Label(window, text="Hello")
helloLabel.pack(side="top")
if __name__ == "__main__": # only runs when this file is run as a standalone
theme = "cyborg"
window = tb.Window(themename=theme) # create a TK object
Main(window) # open the VideoPlayer GUI
window.mainloop() # run the window main loop, reacting to button presses, etc
It is better that
Main
inherits fromtb.Window
andNewWindow
inherits fromtb.Toplevel
. Also you need to check whether the self.newtab is created if you want to call its functionsayhello()
.Below is the modified code: