Home > Mobile >  How do I execute a code within a tk.Toplevel()
How do I execute a code within a tk.Toplevel()

Time:01-16

I'm somewhat new to python (started in Nov.) and after complete my first "program" I'm trying to built the GUI using Tkinter. I want to put the program on a Toplevel that I've created and have it run, but all Tkinter tutorials only talk about widgets and I don't know how to specify that a code should run on a specific Toplevel window. The best I can figure is to run the in the section where I define the Toplevel as shown in the example below, but that is not working.


from tkinter import *
import tkinter as tk
root=Tk()
root.geometry("500x200")
root.title('Test')
Label(root, text="Test").pack()
def test():
    gen_win = Toplevel(root)
    gen_win.title("Test")
    gen_win.geometry("500x500")
    Label(gen_win, text="Test").pack()
    print(2 2)
btn_test=tk.Button(root, text="test", command=test).pack(fill=tk.X)
root.mainloop()

The example program (print(2 2)) doesn't print on the toplevel. Any ideas?

CodePudding user response:

@jasonharper gave the correct answer:

"Code doesn't "run on a specific Toplevel window". It just runs, and if it happens to create a widget, or modify the contents of an existing widget, that change becomes visible as soon as your code returns to the mainloop. Label(gen_win, text=str(2 2)).pack() would be the simplest way to make your addition results visible in the window."

  • Related