我有一个名为main.py
的文件,其中包含一个名为mainWindow
的类。我还有一个名为popupWindow.py
的文件,其中包含一个名为popupWindow
的类。mainWindow
类包含2个方法。一个名为clearListBox
的函数用于清除主窗口中的列表框,另一个名为addScouts(I)
的函数用于将存储在文件中的侦察兵写入列表框。我想能够从我的类popupWindow
调用clearListBox
和addScouts(I)
。我如何做到这一点?你知道吗
在尝试from main import mainWindow
然后调用mainWindow.addScouts(1)
时,我收到了错误addScouts
需要arg self
在我的main.py
文件中:
class mainWindow:
def __init__(self,master):
self.master = master
self._scouts = []
addBtn = Button(master,text="Create Scout",command=self._createScout)
addBtn.pack()
remBtn = Button(master,text="Remove Scout",command=self._removeScout)
remBtn.pack()
fndBtn = Button(master,text="Find Scout",command=self._findScout)
fndBtn.pack()
exitBtn = Button(master,text="Exit",command=self._exit)
exitBtn.pack()
scoutList = Listbox(master)
scoutList.pack()
self.scoutList = scoutList
self.addScouts(1)
w = 1000 #The value of the width
h = 750 #The value of the height of the window
# get screen width and height
ws = root.winfo_screenwidth()#This value is the width of the screen
hs = root.winfo_screenheight()#This is the height of the screen
# calculate position x, y
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
#This is responsible for setting the dimensions of the screen and where it is
#placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
self._createLeaderboard()
def addScouts(self,I):
i = I
with open(fileName,"r") as f:
lines = f.readlines()
for line in lines:
if str(line.split(",")[3])[:-1] == str(i):
self.scoutList.insert(END,line[:-1])
i += 1
return self.addScouts(i)
return
def clearListBox(self):
self.scoutList.delete(0,END)
return
在popupWindow.py
中:
from main import mainWindow
在popupWindow
类中:
mainWindow.clearListBox()
mainWindow.addScouts(1)
我的错误:
Traceback (most recent call last):
File "C:\Users\KRIS\Documents\Python Projects\Scouts\popupWindow.py", line 4, in <module>
from main import mainWindow
File "C:\Users\KRIS\Documents\Python Projects\Scouts\main.py", line 4, in <module>
from popupWindow import *
File "C:\Users\KRIS\Documents\Python Projects\Scouts\popupWindow.py", line 4, in <module>
from main import mainWindow
ImportError: cannot import name 'mainWindow'
先谢谢你
根据你的问题和对@nicegue答案的评论,很明显解决问题的方法是阅读the python tutorial:很快你就会了解模块(包括
import
)和类(包括self
,以及调用类方法)。你知道吗编辑:如果您已经了解了类和实例,那么下面是您的问题:您的类名是
mainWindow
,您的实例是mainWin
。您应该在mainWin
上调用函数,例如mainWin.addScouts(1)
;而不是在mainWindow
。你知道吗在
popupWindow.py
的开头,把然后你可以打电话,例如
mainWindow.clearListBox()
发布代码后编辑示例:
clearListBox
是一个实例方法,因此只能在实例上调用,而不能在类本身上调用。首先必须实例化mainWindow
类型的对象。你知道吗这个问题已经被问了一次又一次,而且没有什么特定于Python的。要对另一个类的实例调用方法,需要对该实例进行引用。非常明显的解决方案是在调用时传递此引用:
或在实例化时:
请注意,在这两种情况下,
B
不需要了解类A
—它只获取一个作为param的实例,仅此而已。因此,如果A
和B
位于不同的模块中,则包含B
的模块不必导入包含A
的模块:这避免了循环导入错误,显然您已经给出了您的回溯。你知道吗
相关问题 更多 >
编程相关推荐