0

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?

3
  • 1
    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. Commented Jan 12, 2023 at 21:00
  • 1
    When I run this and press the button, it prints as expected. The only thing I see wrong here is the imports - you don't need from tkinter import * if you have import tkinter as tk and namespace things correctly with tk. (e.g., root = tk.Tk()). Star imports should be avoided, and import tkinter as tk is the most common practice. Commented Jan 12, 2023 at 21:00
  • @jasonharper makes me think I misunderstood your question! They're right - if you're trying to output the result of 2+2 on the Label on your Toplevel window, print() won't do that, that's not what it's for. Commented Jan 12, 2023 at 21:02

1 Answer 1

0

@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."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.