简体   繁体   中英

Tkinter create_oval method does not change color

I've used buttons so when clicked they change the color of the ovals to obviously draw. The thing is no matter how I change the color variable it would always create a white oval. Any help?

Code:

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()

When you change the value of the color variable in the functions, then the same is not reflected in the main color variable, this is the reason for your problem, since you never tell python that the variable color inside the function and outside the function are the same, so python considers the two to be different one local and the other global.

The one easy fix for the same is to declare to python that you are referring to the global color variable whenever you use it in other functions using the global keyword of python this fixes your problem -:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM