I have a program that opens a window and a circle at the center that is filled green at the start. I want this circle to change from red to green and green to red each time I press a button (r in this code) however I can only change the color once
from tkinter import *
import keyboard
if __name__ == '__main__':
window = Tk()
window.title("On Record")
window.configure(width=500, height=300)
window.configure(bg='lightgray')
myCanvas = Canvas(window)
myCanvas.pack()
def daire(x, y, r, canvasName, color): # center coordinates, radius
x0 = x - r
y0 = y - r
x1 = x r
y1 = y r
return canvasName.create_oval(x0, y0, x1, y1, fill=color)
# move window center
winWidth = window.winfo_reqwidth()
winwHeight = window.winfo_reqheight()
posRight = int(window.winfo_screenwidth() / 2 - winWidth / 2)
posDown = int(window.winfo_screenheight() / 2 - winwHeight / 2)
window.geometry(" {} {}".format(posRight, posDown))
color = "green"
def onKeyPress(event):
print("pressed")
counter = 0
counter = counter 1
print(counter)
if counter % 2 == 0:
color = "green"
else:
color = "red"
daire(190, 135, 120, myCanvas, color)
window.bind("r", onKeyPress)
daire(190, 135, 120, myCanvas, "green")
window.mainloop()
CodePudding user response:
The problem was the event function is reliant on counter being odd or even, but it auto resets it to 0 every time is is run. One solution to this is to place the counter outside of the function and call it as a global.
from tkinter import *
import keyboard
if __name__ == '__main__':
window = Tk()
window.title("On Record")
window.configure(width=500, height=300)
window.configure(bg='lightgray')
myCanvas = Canvas(window)
myCanvas.pack()
def daire(x, y, r, canvasName, color): # center coordinates, radius
x0 = x - r
y0 = y - r
x1 = x r
y1 = y r
return canvasName.create_oval(x0, y0, x1, y1, fill=color)
# move window center
winWidth = window.winfo_reqwidth()
winwHeight = window.winfo_reqheight()
posRight = int(window.winfo_screenwidth() / 2 - winWidth / 2)
posDown = int(window.winfo_screenheight() / 2 - winwHeight / 2)
window.geometry(" {} {}".format(posRight, posDown))
color = "green"
counter = 0
def onKeyPress(event):
global counter
print("pressed")
counter = 1
print(counter)
if counter % 2 == 0:
color = "green"
else:
color = "red"
daire(190, 135, 120, myCanvas, color)
window.bind("r", onKeyPress)
daire(190, 135, 120, myCanvas, color)
window.mainloop()
Out of interest do you actually need to be able to track how many times r is pressed? Its implied by your script but not explicitly stated. Otherwise theres more streamlined ways of doing this by referring directly to tkinter elements, as is often done with button toggles as displayed in this post.
