我正在尝试使用功能change_red更改画布上绘制的Im线的颜色。单击运行该功能的按钮后,self.color的值将变为红色,但是线条仍将绘制为黑色。
我试图在init方法中更改self.color,但它仍然仅以黑色绘制。
from PIL import Image, ImageTk
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.color = "black"
menubar = tk.Menu(self)
self.config(menu=menubar)
operation_menu = tk.Menu(menubar, tearoff=0)
config_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Change Color", menu=operation_menu)
menubar.add_cascade(label="Help", menu=config_menu)
config_menu.add_command(label="Exit", command=lambda: exit())
operation_menu.add_command(label="Red", command=lambda: self.change_red())
self.im = ImageTk.PhotoImage(Image.open("Test.png"))
self.geometry("500x500")
self.title("Image Editor")
self.resizable(False, False)
self.im_cv = tk.Canvas(width=300, height=200)
self.im_cv.pack(expand="yes", fill="both")
self.im_cv.create_image(50, 10, image=self.im, anchor="nw")
self.im_cv.bind("<B1-Motion>", self.paint)
def change_red(self):
self.color = "red"
def paint(self, event):
print(self.color)
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
self.my_canvas = self.im_cv.create_oval(x1, y1,x2,y2, fill=self.color, width=5)
window = Window()
window.mainloop()
答案 0 :(得分:1)
您需要认识到width
函数中的create_oval
属性实际上是 width of the border around the outside of the ellipse. Default is 1 pixel.
,因此,即使颜色已更改,也无法视觉上看。为此,您需要更改椭圆/椭圆的厚度或设置width=0
,即不设边框。这是一个示例:
#I didn't have ImageTk so I have changed it accordingly
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.color = "black"
self.t = 2
menubar = tk.Menu(self)
self.config(menu=menubar)
operation_menu = tk.Menu(menubar, tearoff=0)
config_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Change Color", menu=operation_menu)
menubar.add_cascade(label="Help", menu=config_menu)
config_menu.add_command(label="Exit", command=lambda: exit())
operation_menu.add_command(label="Red", command=lambda: self.change_red())
self.im = tk.PhotoImage(file="ex.png")
self.geometry("500x500")
self.title("Image Editor")
self.resizable(False, False)
self.im_cv = tk.Canvas(self, width=300, height=200)
self.im_cv.pack(expand="yes", fill="both")
self.im_cv.create_image(50, 10, image=self.im, anchor="nw")
self.im_cv.bind("<B1-Motion>", self.paint)
def change_red(self):
self.color = "red"
def paint(self, event):
# print(self.color)
x1, y1 = (event.x - self.t), (event.y - self.t)
x2, y2 = (event.x + self.t), (event.y + self.t)
self.my_canvas = self.im_cv.create_oval(x1, y1, x2, y2, fill=self.color, width=0)
window = Window()
window.mainloop()