Connor Mooneyhan
Connor Mooneyhan

Reputation: 557

TkInter Tk() not working

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

Answers (2)

Deepam Gupta
Deepam Gupta

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

Bryan Oakley
Bryan Oakley

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

Related Questions