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:36

Thought this would help regarding "tk not defined"

from tkinter import *
import tkinter.tkFileDialog
root = tkinter.Tk('Anything you want is displayed')
查看更多
劫难
3楼-- · 2019-02-20 14:36

from tkinter import *

root = Tk()

import with the lowercase t and use uppercase T in TK

this worked for me

查看更多
Root(大扎)
4楼-- · 2019-02-20 14:36

This will work well for Python 3:

from Tkinter import *
import Tkinter as tk

window = tk.Tk()
window.title("Welcome to LikeGeeks app")
window.mainloop()
查看更多
登录 后发表回答