-2
我试图访问另一个类中的函数,并通过“主”类来执行该操作。我已经通过Column 4按钮成功地访问了“master”类,我试图通过列5函数访问主类,然后使其进入窗口类的反应函数,但是当我尝试这样做时,它失败。Python:在另一个类中访问函数
from tkinter import *
class Window():
def __init__(self, parent, parent_class2):
self.parent = parent
self.parent_class = parent_class2
self.canvas = Canvas(self.parent, width=420, height=360)
self.canvas.pack(side="top", fill="both", expand="true")
self.cellwidth = 60
self.cellheight = 60
self.rows = 6
self.columns = 7
self.rect = {}
self.oval = {}
self.piece = []
#creates the grid
for row in range(6):
for column in range(7):
x1 = column*self.cellwidth
y1 = row * self.cellheight
x2 = x1 + self.cellwidth
y2 = y1 + self.cellheight
self.piece.append(Piece(self.canvas, x1,y1,x2,y2))
self.canvas.itemconfig(self.piece[8].oval, fill="deep pink")
def reaction(self):
print("In WIndow Class - SUCCESS!")
class ButtonsExampleGUI:
def __init__(self, parent, parent_class):
self.parent_class = parent_class
self.parent = parent
#self.buttons = 7
c4 = Button(parent,text = ("Column 4"), command = self.c4_played)
c4.pack(side = LEFT)
c5 = Button(parent,text = ("Column 5"), command = self.c5_played)
c5.pack(side = LEFT)
def c4_played(self):
self.parent_class.test()
print("Col 4")
def c5_played(self):
print("Col 5")
self.parent_class.towindow()
class Piece:
def __init__(self, parent_canvas, x1,y1,x2,y2):
self.parent_canvas = parent_canvas
self.rect = self.parent_canvas.create_rectangle(x1,y1,x2,y2, fill="grey", tags="rect")
self.oval = self.parent_canvas.create_oval(x1+2,y1+2,x2-2,y2-2, fill="white", tags="oval")
#self class here is being taken as the "parent_class" of the ButtonExampleGUI class
class Game:
def __init__(self, parent):
self.parent = parent
self.window = Window (self.parent, self)
self.buttons = ButtonsExampleGUI (self.parent, self)
#test being accessed by c4 function calling this within a different class
def test(self):
print("from parent class")
def towindow(self):
print("In Game Class")
self.parent_class2.reaction()
if __name__ == "__main__":
root = Tk()
game = Game(root)
root.mainloop()
你能提供有关此失败的具体方式更详细?如果有例外,你可以提供这个例外吗? –
@ eric-scrivner下面是错误'Tkinter回调中的异常 Traceback(最近调用最后一次): __call__中的第1533行文件“C:\ Python34 \ lib \ tkinter \ __ init__.py”返回self.func * args) 文件“H:\ 2015 DTS \ 3.46 \ C4 Revisions \ 4May.py”,第77行,在c5_played中 self.parent_class.towindow() 文件“H:\ 2015 DTS \ 3.46 \ C4 Revisions \ 4May .py“,第109行,在towindow中 self.parent_class2.reaction() AttributeError:'游戏'对象没有任何属性'parent_class2'' – PaddyGower
应该使用类游戏扩展tkinter吗? – Scott