我很好奇是否有办法直接在其中反转画布的颜色。我已经看到了PIL模块,它允许处理图像(作为文件(,但我想应用在包含形状的画布内仍然可见的更改。 例如:
import tkinter
canvas=tkinter.Canvas()
canvas.pack()
canvas.create_rectangle(20,20,60,60,fill='blue', outline='red')
你能帮帮我,如何反转颜色吗?
有趣的问题。我一次只能更改一个画布项目的颜色,但我可以编写一个执行全部或部分画布的函数。例:
import tkinter
root = tkinter.Tk()
root.geometry('300x200')
canvas = tkinter.Canvas()
canvas.pack(expand='yes', fill='both')
canvas.create_rectangle(20,20,60,60,fill='blue', outline='red')
canvas.create_line(100,100,160,160,fill='blue')
def invert_color(color): # Invert color
if type(color) == str: rgb = canvas.winfo_rgb(color)
else: rgb = color
rgb = (65535-rgb[0], 65535-rgb[1], 65535-rgb[2])
tk_rgb = "#%04x%04x%04x" % (rgb)
return tk_rgb
def invert_canvas(event):
# Check or select canvas items:
items = canvas.find_withtag('all')
# Loop through canvas items
for item in items:
fill = canvas.itemcget(item, "fill") # Get fill color
if fill != '': fill = invert_color(fill)
if canvas.type(item) in ['rectangle','arc']:
outline = canvas.itemcget(item, "outline") # Get outline color
outline = invert_color(outline)
canvas.itemconfig(item, fill=fill, outline=outline) # Set colors
else:
canvas.itemconfig(item, fill=fill) # Set colors
root.bind('<space>', invert_canvas)