tkinter画布项目配置
我正在尝试制作一个骰子对象,并且我想控制骰子点的颜色。我用黑色填充创建了这些点,然后我试着用
self.canvas.itemconfigure(self.pip1, fill='red')
把其中一个点改成红色,但似乎没有效果。没有错误提示,所以我在想为什么这个颜色的变化没有显示出来。
最小可工作示例:
from tkinter import *
from tkinter import ttk
class Dice:
#the x and y instancing variables are for the x and y coordinates of the top left corner of the rectangle
def __init__(self, win, x, y):
self.win = win
self.win.geometry("500x500")
self.canvas = Canvas(self.win)
self.canvas.place(x=0, y=0)
die = self.canvas.create_rectangle(x, y, x+88, y+88, fill='white', width=1)
offset = 20
#create 7 circles for pip locations:
self.pip1 = self.pips(x+offset, y+offset)
self.pip2 = self.pips(x+offset, y+2*offset)
self.pip3 = self.pips(x+offset, y+3*offset)
self.pip4 = self.pips(x+2*offset, y+2*offset)
self.pip5 = self.pips(x+3*offset, y+offset)
self.pip6 = self.pips(x+3*offset, y+2*offset)
self.pip7 = self.pips(x+3*offset, y+3*offset)
self.canvas.itemconfigure(self.pip1, fill='red')
def pips(self, x, y):
pip = self.canvas.create_oval(x, y, x+9, y+9, fill='black', width=0)
#def setValue(self, value)
#def pipsOff(self, pip):
def test():
x = Dice(Tk(), 50, 50)
mainloop()
1 个回答
1
调试的第一条规则是:检查你的数据。如果你在调用 itemconfigure
之前加一个打印语句,或者在调试器里停下来,你会发现 self.pip1
的值是 None
。所以你首先要问自己,“为什么它是 None
?”
它之所以是 None
,是因为你在一个方法里创建了它,但忘记返回这个项目的 ID。因此,解决这个问题的方法是在函数 pips
的最后加上 return pip
:
def pips(self, x, y):
pip = self.canvas.create_oval(x, y, x+9, y+9, fill='black', width=0)
return pip