矩形的填充颜色虽然设置为红色,但仍保持黑色

时间:2018-12-17 01:08:58

标签: python tkinter

(摘录自我程序的代码)

global pensize
global rect1
try:
    pensize
except:
    pensize = 0
global pencolor
try:
    pencolor
except:
    pencolor = "red"
def callback(event):
    global rect1
    rect1 = canvas.create_rectangle(event.x-pensize, event.y-pensize, event.x+pensize, event.y+pensize, fill="red")
    print(pencolor)
def setpencolor(color):
    global pencolor
    pencolor = color
    global rect1
    canvas.itemconfig(rect1, fill=pencolor)
    print("Pencolor set to"+str(pencolor))

#    --- window properties ---
# --- the canvas ---
canvas= Canvas(root, width=600, height=600)
canvas.bind("<B1-Motion>", callback)
canvas.pack(side = RIGHT)
# --- the menubar ---
menubar = Menu(root)
menubar.add_command(label="Exit", command=root.quit)
#   --- color tool---
colormenu = Menu(menubar, tearoff=0)
colormenu.add_command(label="Black", command=lambda: setpencolor("black"))
colormenu.add_command(label="Red", command=lambda: setpencolor("red"))
colormenu.add_command(label="Blue", command=lambda: setpencolor("blue"))
menubar.add_cascade(label="Color", menu=colormenu)

这是我正在制作的绘图程序的一部分。我想这样做,以便当用户更改颜色时,它不仅更改笔的颜色,还更改他们绘制的所有其他内容。但是,这些概念都不起作用。即使pencolor明确设置为“红色”,矩形的填充颜色仍保持黑色。尽管它应该改变其他所有颜色,但它绝对不起作用。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

欢迎来到stackoverflow!

在玩完示例之后,我相信这与笔的大小有关。您只会看到始终为黑色的边框。我已经简化了您的示例,以下内容几乎可以按预期进行。注意每个矩形周围的黑色边框吗?这就是您要更改的内容。

import tkinter as tk 

root = tk.Tk()

# --- the canvas ---
canvas = tk.Canvas(root, width=600, height=600)
canvas.grid()

global pensize, pencolor
pensize = 3
pencolor = 'red'

def callback(event):
    canvas.create_rectangle(
        event.x-pensize, event.y-pensize, 
        event.x+pensize, event.y+pensize, 
        fill=pencolor, outline=pencolor)

def setpencolor(color, canvas):
    global pencolor
    pencolor = color

    elements = canvas.find_all()

    for element in elements:
        canvas.itemconfigure(element, fill=color, outline=color)

canvas.bind("<B1-Motion>", callback)

# --- color tool---
tk.Button(root, text='black', 
    command=lambda: setpencolor("black", canvas)).grid()
tk.Button(root, text='red', 
    command=lambda: setpencolor("red", canvas)).grid()
tk.Button(root, text='blue', 
    command=lambda: setpencolor("blue", canvas)).grid()

root.mainloop()

现在,尝试如下创建矩形:

canvas.create_rectangle(
    event.x-pensize, event.y-pensize, 
    event.x+pensize, event.y+pensize, 
    fill=pencolor, outline=pencolor
)

要回答问题的最后一部分,现在必须在画布上找到所有元素,并使用itemconfigure更改其属性:

elements = canvas.find_all()

for element in elements:
    canvas.itemconfigure(element, fill=color, outline=color)