我正在製作一個TKinter應用程序,並已開始使用類來構造我的代碼。我想通過不在同一個文件中包含所有東西來保持可讀性,但是當我在main_frontend.py中運行代碼時發生此錯誤:AttributeError:'module'object has no attribute'calWin' 以下是main_frontend.py中的代碼:AttributeError:'模塊'對象沒有屬性'calWin'
import windows
import tkinter as tk
from tkinter import ttk
class app(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
frame = windows.calWin(container, self)
self.frames[windows.calWin] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(windows.calWin)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
win = app()
win.mainloop()
這裏是windows.py代碼:
import passing
import tkinter as tk
from tkinter import ttk
class calWin(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
calVar = StringVar()
calEnt = Entry(self, textvariable=calVar)
calEnt.pack()
calBut = Button(self, text='Calculate', command=lambda: passing.calPass(calVar.get(), calEnt, calLabel))
calBut.pack()
calLabel = Label(self)
calLabel.pack()
而且從passing.py:
import core
def calPass(gtin, calEnt, calLabel):
if gtinValidate(gtin, 7):
calLabel.configure(text='The Full GTIN Number Is '+core.calculate(gtin))
calEnt.delete(0, END)
else:
calLabel.configure(text='GTIN Invalid')
而且從core.py:
def calculate(gtin):
'''
Calculates the check digit of a GTIN-8 number
'''
x = (int(gtin[0])+int(gtin[2])+int(gtin[4])+int(gtin[6]))*3
x += int(gtin[1])+int(gtin[3])+int(gtin[5]) #Adds every other number in code
remainder = x%10 #Finds how far check digit is away from nearest multiple of ten
gtin = list(gtin)
if remainder != 0:
gtin.append(str(10-remainder))#Adds check digit to end of code if remainder is more than 0
else:
gtin.append('0')
return(''.join(gtin))
這裏是我的錯誤的細節,當我從main_frontend.py運行代碼:
Traceback (most recent call last):
File "H:\PythonCode\Stock Control Task\Organised GTIN TKinter GUI Project\main_frontend.py", line 33, in <module>
win = app()
File "H:\PythonCode\Stock Control Task\Organised GTIN TKinter GUI Project\main_frontend.py", line 22, in __init__
frame = windows.calWin(container, self)
AttributeError: 'module' object has no attribute 'calWin'
幫助?
你確定你正在導入的'windows'是你認爲它的文件嗎?你可以在你的代碼中加入'print(windows .__ file __)'來查看正在導入的文件。 –
你爲什麼將'self'傳遞給'calWin'? –
是的,我確定它是相同的文件,因爲我用windows .__ doc__測試了它,並且它打印了我的文檔。我將自己傳遞給calWin,因爲我聲明calWin是tk.Frame()類的一個實例,所以我想要的任何窗口小部件的父窗體實際上就是它自己,所以我把它放在了自己的位置。 – PySheep