Programming in Python: Getting “name 'Tk'

2019-02-20 13:54发布

A question from a beginner just starting with Tkinter. I downloaded it and wrote the tutorial Hello World program, and it ran fine in IDLE. However, when I saved the program and ran it using command prompt, they all returned NameError: name 'tk' is not defined. I also tried going to the main Python command program and manually entering the code, and it worked fine.

It only fails to recognize Tk() when run through command prompt or through double clicking.

I have no idea what could be going on here.

The code is simply the basic Hello World program that all tutorials teach you to write:

from Tkinter import *
root = Tk()
w = Label(root, text="Hello World")
w.pack()

root.mainloop()

Also because I know everybody is going to answer with it, I am not using 3.x and I have tried running the program with calling it "tkinter," it simply doesn't find the module.

Apparently this program works on other people's computers, so it's not a problem with the code itself. Does anyone have any idea what could be causing this issue?

9条回答
该账号已被封号
2楼-- · 2019-02-20 14:15

I was having the same problem and couldn't find any solution until I simply changed this:

from Tkinter import *

to:

from tkinter import *

I don't know the capital T works for other but under Windows 64 bit Python 3.4.1, it should be "tkinter"

查看更多
对你真心纯属浪费
3楼-- · 2019-02-20 14:26

Also check your file name if you created tkinter.py before, then it can also cause same issue. It would be imported first

查看更多
Summer. ? 凉城
4楼-- · 2019-02-20 14:28

Works fine in my computer .

Since You said : NameError: name 'tk' is not defined.

here tk with a small 't'

You might have written

root = tk()

instead of :

root = Tk()

Check Capital 'T'

查看更多
冷血范
5楼-- · 2019-02-20 14:32

Python is distributed with different builds, some of which include Tkinter and some don't.

What your describing is symptomatic of having multiple Python's on your system. When you run IDLE, obviously you're running one with Tkinter installed. The one available at the command-line apparently doesn't. One way to confirm this is to try to launch IDLE from the command-line: python -m idlelib.idle. If IDLE doesn't launch, the Tkinter isn't installed and you will need to find a path to the version that does run IDLE successfully.

查看更多
Luminary・发光体
6楼-- · 2019-02-20 14:34

I suppose this is something to do with

  1. the python version one is using
  2. how you basically imported the library

For python 2.x use this

from Tkinter import *

root = Tk()

root.mainloop()

OR

from tkinter import *

root = tkinter()

root = mainloop()
查看更多
时光不老,我们不散
7楼-- · 2019-02-20 14:36

For Python 2.x use:

from Tkinter import * as tk
import Tkinter as tk
root = Tk()

For Python 3 use:

from tkinter import * as tk
import tkinter as tk
root = tk.Tk()
查看更多
登录 后发表回答