簡體   English   中英

tkinter canvas 項目配置

[英]tkinter canvas item configure

我正在嘗試做一個骰子object,我希望能夠控制pip colors。 我用黑色填充創建了點,並嘗試使用將點更改為紅色

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()

調試的第一條規則:檢查你的數據。 如果您在調用itemconfigure之前放置打印語句或停止調試器,您將看到self.pip1的值為None 所以你應該問自己的第一件事是,“為什么是None ?”

它是None的原因是您在方法中創建它但忽略返回項目 ID。 因此,解決您的問題的方法是在 function 點的末尾添加return pip pips

def pips(self, x, y):
    pip = self.canvas.create_oval(x, y, x+9, y+9, fill='black', width=0)
    return pip

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM