I'm trying to make a dice object, and I want to be able to control the pip colors. I created the pips with a black fill, and I tried to change one to red using
self.canvas.itemconfigure(self.pip1, fill='red')
but it seems to have no effect. There is no error so I'm wondering why the change doesn't show up.
Minimum working example:
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()
First rule of debugging: examine your data. If you put a print statement or stop the debugger just before the call to
itemconfigure
you will see thatself.pip1
has a value ofNone
. So the first thing you should ask yourself is, "why is itNone
?"The reason it is
None
is that you create it in a method but neglect to return the item id. So, the fix to your problem is to addreturn pip
at the end of the functionpips
: