誠然,我是 Python 的菜鳥,但我知道這里發生了一些愚蠢的事情,我在谷歌上找不到任何幫助。我想要做的就是將 Tkinter 用于一個簡單的 GUI,但是當我嘗試匯入并使用一個函式時遇到 Import 錯誤時,很難做到這一點。
我用我自己的命名等遵循了這個教程:
#testUI.py
from tkinter import *
from test2 import nameit
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
#test2.py
def nameit(name):
greeting = name
return greeting
使用這個產生:
ImportError: cannot import name 'nameit' from 'test2'
我嘗試過的另一種方法是僅使用“匯入”
from tkinter import *
import test2
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = test2.nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
這也會產生一個錯誤:
AttributeError: module 'test2' has no attribute 'nameit'
我真的不知道該怎么做,我幾乎肯定這是愚蠢的,但我一生都無法在谷歌、stackoverflow 或其他任何地方找到任何東西。
10000 一生的繁榮給任何可以幫助我的人。謝謝!
uj5u.com熱心網友回復:
您提供的示例對我有用,但是,此問題可能是由于您在test2.py檔案中進行的某些匯入。
例如,在testUI.py您正在匯入test2和在test2.py您正在匯入testUI. 你需要想辦法打破這個回圈,減少依賴。
一個例子如下所示:
# testUI.py
from tkinter import *
from test2 import nameit
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
# test2.py
import testUI # Extra import statement
def nameit(name):
greeting = name
return greeting
當你運行時test2.py,你會得到想要的結果。testUI.py但是,當您運行時,您會收到以下錯誤:
from test2 import nameit
ImportError: cannot import name 'nameit' from partially initialized module 'test2' (most likely due to a circular import)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405990.html
標籤:
上一篇:在python中生成變數?
