當我嘗試運行腳本以查看是否可以tkinter在 VsCode 上使用時,它會拋出一個NameError說法name 'Tk' is not defined。此外,我可以在 IDLE 上運行它,它運行得很好。我一直在四處尋找是否可以修復它,但我仍然無法使其正常作業。你知道我做錯了什么嗎?
這是代碼:
from tkinter import *
root = Tk()
myLabel = Label(root, text = 'Hello World!')
myLabel.pack()
uj5u.com熱心網友回復:
不要命名您的檔案,tkinter.py因為您嘗試匯入的 tkinter 模塊實際上是在匯入檔案本身。而且由于Tk您的檔案中沒有呼叫任何函式,因此您會收到該錯誤。將檔案重命名為其他名稱。
例如,將其重命名為gui.py.
另外,在python中最好是顯式而不是隱式。所以代替
# Pollutes your namespace
# May clash with the functions you define or functions of other libraries that you import
from tkinter import *
root = Tk()
...
你應該使用
import tkinter as tk
root = tk.Tk()
...
這是它如何與其他命名空間發生沖突的示例:
from tkinter import *
root = Tk()
Label = "hello"
Label1 = Label(gui, text=Label)
這會導致錯誤:
Traceback (most recent call last):
File "stackoverflow.py", line 98, in <module>
Label1 = Label(gui, text=Label)
TypeError: 'str' object is not callable
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398950.html
