我使用过按钮,所以当点击时,它们会改变椭圆形的颜色,以明显地绘制。问题是,无论我如何改变颜色变量,它总是会创建一个白色的椭圆形。有什么帮助吗?
代码:
from tkinter import *
master = Tk()
master.title('Painting in Python')
canvas_width = 600
canvas_height = 450
color='white'
bg ='black'
def REDPEN():
color='red'
print(color)
def BLUEPEN():
color='blue'
print(color)
def GREENPEN():
color='green'
print(color)
def paint(event):
x1,y1=(event.x-1),(event.y-1)
x2,y2=(event.x+1),(event.y+1)
c.create_oval(x1,y1,x2,y2,fill=color,outline=color,width=0)
RedButton = Button(master, text = "RED", command =REDPEN)
BlueButton = Button(master, text = "BLUE", command =BLUEPEN)
GreenButton = Button(master, text = "GREEN", command =GREENPEN)
RedButton.pack()
BlueButton.pack()
GreenButton.pack()
c=Canvas(master,width=canvas_width,height=canvas_height,bg=bg)
c.pack(expand=YES,fill=BOTH)
c.bind('<B1-Motion>',paint)
message=Label(master,text='Press and Drag to draw')
message.pack(side=BOTTOM)
master.mainloop()发布于 2021-05-03 22:39:39
当您更改函数中的color变量的值时,相同的值不会反映在主颜色变量中,这就是出现问题的原因,因为您从未告诉python函数内部和函数外部的变量color是相同的,因此python认为这两者是不同的,一个是局部的,另一个是全局的。
解决这个问题的一个简单方法是,在其他函数中使用全局颜色变量时,向python声明您引用的是全局颜色变量,使用全局关键字python可以修复您的问题-:
from tkinter import *
master = Tk()
master.title('Painting in Python')
canvas_width = 600
canvas_height = 450
color='white'
bg ='black'
def REDPEN():
global color
color='red'
print(color)
def BLUEPEN():
global color
color='blue'
print(color)
def GREENPEN():
global color
color='green'
print(color)
def paint(event):
global color
x1,y1=(event.x-1),(event.y-1)
x2,y2=(event.x+1),(event.y+1)
c.create_oval(x1,y1,x2,y2,fill=color,outline=color,width=0)
RedButton = Button(master, text = "RED", command =REDPEN)
BlueButton = Button(master, text = "BLUE", command =BLUEPEN)
GreenButton = Button(master, text = "GREEN", command =GREENPEN)
RedButton.pack()
BlueButton.pack()
GreenButton.pack()
c=Canvas(master,width=canvas_width,height=canvas_height,bg=bg)
c.pack(expand=YES,fill=BOTH)
c.bind('<B1-Motion>',paint)
message=Label(master,text='Press and Drag to draw')
message.pack(side=BOTTOM)
master.mainloop()https://stackoverflow.com/questions/67370694
复制相似问题