Reputation: 557
I have much experience with Python, but I'm just now learning Tkinter and the following code isn't working:
root = Tk()
root.mainloop()
It spits out the error message "NameError: name 'Tk' is not defined"
Upvotes: 1
Views: 7904
Reputation: 2692
The error occurred because the file was named as tkinter.py
and caused the tkinter
library import to fail.
Make sure your file name differs.
Upvotes: 3
Reputation: 385900
It seems you are simply not importing the tkinter library.
The quick solution is to add from tkinter import *
to the top of your file.
However, global imports are generally a bad idea. I know lots of tkinter tutorials start out this way, but they shouldn't. I recommend doing it this way:
import tkinter as tk
root = tk.Tk()
root.mainloop()
It requires that you prefix every tkinter command with tk.
, but it makes your code easier to understand, and easier to maintain over time. If, for example, you decide to import ttk
(some modern looking tkinter widgets), it is impossible to know if Button(...)
refers to the ttk button or the tk button if you use global imports. However, tk.Button(...)
and ttk.Button(...)
are crystal clear.
Upvotes: 4