据我了解,类DiceRoller
应该从类die
继承,但是每次运行时,我都会收到错误消息:
self.display.config(text = str(self.value))
AttributeError: 'DiceRoller' object has no attribute 'display'
self.value
的值正在更新,但Tkinter标签未更新。import Tkinter
import random
class die(object):
def __init__(self,value,display):
self.value = random.randint(1,6)
self.display = Tkinter.Label(display,
text = str(self.value),
font = ('Garamond', 56),
bg = 'white',
relief = 'ridge',
borderwidth = 5)
self.display.pack(side = 'left')
class DiceRoller(die):
def __init__(self):
self.gameWin = Tkinter.Tk()
self.gameWin.title('Dice Roller')
self.gameFrame = Tkinter.Frame(self.gameWin)
self.dice = []
self.Row1 = Tkinter.Frame(self.gameWin)
for i in range(1,4):
self.dice.append(die(i,self.Row1))
self.topFrame = Tkinter.Frame(self.gameWin)
self.rollBtn = Tkinter.Button(self.topFrame,
text = 'Roll Again',
command = self.rollDice,
font = ('Garamond', 56))
self.rollBtn.pack(side = 'bottom')
self.gameFrame.pack()
self.Row1.pack()
self.topFrame.pack()
self.gameWin.mainloop()
def rollDice(self):
self.value = random.randint(1,6)
print self.value #to show value is in fact changing
self.display.config(text = str(self.value))
varName = DiceRoller()
最佳答案
你明白了
AttributeError: 'DiceRoller' object has no attribute 'display'
错误,因为
DiceRoller
实际上没有.display
属性。您可能希望它具有一个,因为
die
类具有.display
属性,但是该属性是在调用die.__init__
时创建的,并且DiceRoller
不会自动调用die.__init__
,因为您已覆盖了该属性。 DiceRoller
自己的.__init__
方法。如果要在
die.__init__
内部调用DiceRoller.__init__
,则可以这样做,建议的方法是使用super
函数。但是您必须小心使用正确的参数调用die.__init__
!但是,不需要
DiceRoller
从die
继承。我已经将DiceRoller
的旧rollDice
方法移至die
并为rollDice
创建了新的DiceRoller
方法。因此,当按下'Roll Again'
按钮时,DiceRoller.dice
中的所有骰子都会滚动。import Tkinter as tk
import random
class die(object):
def __init__(self, value, display):
self.value = random.randint(1,6)
self.display = tk.Label(display,
text = str(self.value),
font = ('Garamond', 56),
bg = 'white',
relief = 'ridge',
borderwidth = 5)
self.display.pack(side = 'left')
def rollDice(self):
self.value = random.randint(1,6)
print self.value #to show value is in fact changing
self.display.config(text = str(self.value))
class DiceRoller(object):
def __init__(self):
self.gameWin = tk.Tk()
self.gameWin.title('Dice Roller')
self.gameFrame = tk.Frame(self.gameWin)
self.dice = []
self.Row1 = tk.Frame(self.gameWin)
for i in range(1,4):
self.dice.append(die(i, self.Row1))
self.topFrame = tk.Frame(self.gameWin)
self.rollBtn = tk.Button(self.topFrame,
text = 'Roll Again',
command = self.rollDice,
font = ('Garamond', 56))
self.rollBtn.pack(side = 'bottom')
self.gameFrame.pack()
self.Row1.pack()
self.topFrame.pack()
self.gameWin.mainloop()
def rollDice(self):
for die in self.dice:
die.rollDice()
DiceRoller()