Home > front end >  I'm getting a NameError saying name 'Tk' is not defined when I'm trying to use T
I'm getting a NameError saying name 'Tk' is not defined when I'm trying to use T

Time:12-31

When I'm trying to run a script to see if I can use tkinter on VsCode it throws a NameError saying name 'Tk' is not defined. Furthermore I can run it on IDLE and it runs just fine. I've been searching around to see if I can fix it but I still can't get it working. Do you have any idea what I'm doing wrong?

Here is the code:

from tkinter import *

root = Tk()
myLabel = Label(root, text = 'Hello World!')
myLabel.pack()

CodePudding user response:

Do NOT name your file tkinter.py because the tkinter module you are trying to import is actually importing the file itself. And since there's no function called Tk in your file, you are getting that error. Rename the file to something else.

For example, rename it to gui.py.

Also, it's better to be explicit rather than implicit in python. So instead of

# Pollutes your namespace 
# May clash with the functions you define or functions of other libraries that you import

from tkinter import * 

root = Tk()
...

you should use

import tkinter as tk

root = tk.Tk()
...

Here's an example of how it can clash with other namespaces:

from tkinter import *

root = Tk()
Label = "hello"
Label1 = Label(gui, text=Label)

This results in an error:

Traceback (most recent call last):
   File "stackoverflow.py", line 98, in <module>
     Label1 = Label(gui, text=Label)
 TypeError: 'str' object is not callable
  • Related