I am trying to create a function where if I press "1" my image changes, but if I press 1 again the image reverts back to how it was. This process should go on indefinitely.
I am able to do this if the user clicks on a button. For example, the below code simply uses config to change the function that should be run each time button is clicked.
# run this "thing" each time seat is activated
def activate(name):
name.config(image=active)
name.config(command=lambda: deactivate(name))
# run this "thing" each time seat is deactivated
def deactivate(name):
name.config(image=deactive)
name.config(command=lambda: activate(name))
x = Button(root, image=deactive, command=lambda: thing(x))
But I am unable to achieve the same if I bind a key instead:
from tkinter import *
# window config
root = Tk()
root.title("Example - on / off")
root.geometry("1080x600")
# on and off images
inactive = PhotoImage(file='green.png')
active = PhotoImage(file='red.png')
# functions to change the image using config
def something(event):
my_label.config(image=active)
def something2():
my_label.config(image=inactive)
# label which stores the image
my_label = Label(root, image=inactive)
my_label.pack()
# invisible button bind to key "1"
my_button = Button(root)
my_button.bind_all(1, something)
my_button.pack()
root.mainloop()
I would welcome any thoughts on this or an indication if I am approaching this completely wrong.
Thanks
You can simplify the logic by using itertools.cycle()
and next()
functions:
from tkinter import *
from itertools import cycle
root = Tk()
root.title("Example - on / off")
root.geometry("1080x600")
# on and off images
images = cycle((PhotoImage(file='green.png'), PhotoImage(file='red.png')))
def something(event):
my_label.config(image=next(images))
my_label = Label(root, image=next(images))
my_label.pack()
root.bind('1', something)
root.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.