据我了解,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()
关于python - 为什么我的 Tkinter 标签没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533955/