Search code examples
pythontkinterbackground-imagerootswap

How to detect keyboard press in python window?


from tkinter import *

root = Tk()
root.title('FAS')
root.geometry("600x650")

#root.attributes('-alpha', 0.5)
root.wm_attributes("-topmost", True)
root.lift()
root.wm_attributes("-transparentcolor", "grey")

#background image
bg = PhotoImage(file="3MtoCW.png")

 
#this is to make the background image transparents
red_frame = Frame(root, width=600, height=650, bg='grey')
red_frame.place(x=0, y=0)
my_label = Label(root, image=bg, bg='grey')
my_label.place(x=0, y=0)

root.mainloop()

I want that when I press a key in the tkinter window, the original background image "3MtoCW.png" will swap to a new background image called "3MswCW.png" How can I do that?


Solution

  • You need to create a function that would change the Label's configuration on keypress and bind this function to the Event

    The below should do the trick

    from tkinter import *
    
    root = Tk()
    root.title('FAS')
    root.geometry("600x650")
    
    # root.attributes('-alpha', 0.5)
    root.wm_attributes("-topmost", True)
    root.lift()
    root.wm_attributes("-transparentcolor", "grey")
    
    bg_images = ["3MtoCW.jpg", "3MswCW.jpg"]
    
    idx = 0
    # background image
    bg = PhotoImage(file="3MtoCW.png")
    
    red_frame = Frame(root, width=600, height=650, bg='red')
    red_frame.place(x=0, y=0)
    
    my_label = Label(root, image=bg, bg='grey')
    my_label.place(x=0, y=0)
    
    
    def keypress(e):
        print("called")
        global idx
        idx = (idx + 1) % 2
        my_label.config(image=PhotoImage(file=bg_images[idx]))
    
    
    red_frame.bind("<KeyPress>", keypress)
    red_frame.pack()
    red_frame.focus_set()
    root.mainloop()