Elad Elmakias
Elad Elmakias

Reputation: 37

why does tkinter widgets doesnt appear in vscode?

from tkinter import *
from tkinter import ttk

root = Tk()
root.mainloop()
button1 = ttk.Label(root, text = 'lol')
button1.pack()

And when i try to run the program only the window show up but without the button.
it gives me this error:

Exception has occurred: TclError
NULL main window
  File "C:\Users\Elad\Desktop\coding\tkintertut.py", line 6, in <module>
    button1 = ttk.Label(root, text = 'lol')

Upvotes: 0

Views: 695

Answers (2)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

The root.mainloop() has to be at the end of the code for the window to be shown, not right after declaration of root.

from tkinter import *
from tkinter import ttk

root = Tk()

button1 = ttk.Label(root, text = 'lol')
button1.pack()

root.mainloop()

Explanation:

Only the lines of code between root and root.mainloop() gets executed as long as the window is open, if you close the window, the Labels and all other widget declared after root.mainloop() become active but, the window is now closed and root is destroyed, hence the error. But here in my answer, the code between root and root.mainloop() has everything I need to be in the window and hence it shows the complete window. Just keep in mind to always say root.mainloop() at the end of the code only

Hope it cleared your errors. Do let me know if any more errors or doubts.

Cheers

Upvotes: 1

Ibrahim Khaleelulah
Ibrahim Khaleelulah

Reputation: 11

Your root.mainloop() should be the last code!

from tkinter import *
from tkinter import ttk

root = Tk()
button1 = ttk.Label(root, text = 'lol')
button1.pack()
root.mainloop()

Upvotes: 0

Related Questions