考慮這個簡單的代碼Tkinter的TTK:當我運行這段代碼它顯示錯誤爲什麼顯示蟒蛇「名TTK沒有定義」 3.5.1
ttk.Label(root, text='Heading Here').grid(row=1, column=1)
NameError: name 'ttk' is not defined
考慮這個簡單的代碼Tkinter的TTK:當我運行這段代碼它顯示錯誤爲什麼顯示蟒蛇「名TTK沒有定義」 3.5.1
ttk.Label(root, text='Heading Here').grid(row=1, column=1)
NameError: name 'ttk' is not defined
當你做import X
,要導入一個名爲X
模塊。從這一點開始,X
將被定義。
當你做from X import *
,你是不是進口X
,你只進口是內的X
的事情。 X
本身將是未定義的。
因此,當你做from tkinter.ttk import *
,你是不是進口ttk
,你只導入東西 TTK 。這將導入諸如Label
,Button
等,但是而不是ttk
本身。
在python3進口ttk
正確的方法是使用下面的語句:
from tkinter import ttk
有了這一點,你可以用ttk.Label
,該TTK按鈕ttk.Button
等
引用TTK標籤備註:做from tkinter.ttk import *
是危險的。不幸的是,ttk
和tkinter
都導出類具有相同的名稱。如果您同時使用from tkinter import *
和from tkinter.ttk import *
,則您將覆蓋另一個課程。導入順序將改變您的代碼行爲方式。
由於這個原因 - 特別是在tkinter和ttk中,每個類有幾個重疊的類 - 應避免通配符導入。 PEP8,官方Python風格指南,正式鼓勵進口通配符:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
注意:你的問題意味着你使用Python 3中,但如果你正在使用Python 2,你可以做import ttk
而比from tkinter import ttk
。在python 3中移動了ttk
。
要導入ttk
from tkinter import *
from tkinter.ttk import *
root= Tk()
ttk.Label(root, text='Heading Here').grid(row=1, column=1)
ttk.Separator(root,orient=HORIZONTAL).grid(row=2, columnspan=5)
root.mainloop()
中,將以下線:
from tkinter.ttk import *
與:
from tkinter import ttk
否則,tkinter.ttk
模塊的屬性將被加載到當前模塊名稱空間中,而不是ttk
本身。
我做了,但仍然顯示相同的錯誤 – sujit
ttk.Label(root, text='HeadingHere').grid(row=1, column=1)
NameError: name 'ttk' is not defined
In this remove ttk as follows.
Label(root, text='HeadingHere').grid(row=1, column=1
現在它工作正常
這實際上並不回答問題,它只是提供了一種解決方法。 –
我同意你的答案,但是當使用從tkinter導入ttk的行我geting相同的錯誤'Separator(self,orient = HORIZONTAL).grid(row = 0,columnspan = 5,sticky =「ew」) NameError:name '分隔符'沒有定義',你能建議我克服這個錯誤@BryanOakley – sujit
@ sujit:使用'ttk.Separator' –
我試圖說我得到錯誤'名稱ttk沒有定義'@ Bryan – sujit