tkinter 画布项目配置 [英] tkinter canvas item configure

查看:35
本文介绍了tkinter 画布项目配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个骰子对象,并且我希望能够控制点子颜色.我用黑色填充创建了点子,并尝试使用

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.

最小工作示例:

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?"

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 that self.pip1 has a value of None. So the first thing you should ask yourself is, "why is it None?"

它是 None 的原因是你在一个方法中创建它但忽略了返回项目 id.因此,解决您的问题的方法是在函数 pips 的末尾添加 return pip:

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 add return pip at the end of the function pips:

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

这篇关于tkinter 画布项目配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆