繁体   English   中英

Python GUI - 如何通过按下键盘输入来更改按钮的颜色?

[英]Python GUI - How to change a button's colour by pressing a keyboard input?

我在 Python 中编写了一个程序,其中我有一个显示 4 个按钮(左上右下)的 GUI,当我从键盘按下它们时,它们会返回一条消息。 我想要的是,当我按下按钮时,我希望框字段以红色或其他颜色+显示按下哪个按钮的消息。

from tkinter import *


window = Tk()
window.title("Arrow Keys")
window.geometry('820x640')
width = 820
height = 640


myButton1 = Button(window, text="    UP   ", activebackground='red')
myButton1.place(x= 387, y=10)
myButton2 = Button(window, text="DOWN", activebackground='red')
myButton2.place(x= 399, y= 60)
myButton2.pack(pady=60)
myButton3 = Button(window, text=" LEFT ", activebackground='red')
myButton3.place(x= 345, y=35)
myButton4 = Button(window, text="RIGHT", activebackground='red')
myButton4.place(x= 435, y= 35)

def up(event):
    myLabel = Label(window, text="Press UP")
    myLabel.pack()

def down(event):
    myLabel = Label(window, text="Press DOWN")
    myLabel.pack()

def left(event):
    myLabel = Label(window, text="Press LEFT")
    myLabel.pack()

def right(event):
    myLabel = Label(window, text="Press RIGHT")
    myLabel.pack()

window.bind("<Up>", up)
window.bind("<Down>", down)
window.bind("<Left>", left)
window.bind("<Right>", right)

window.mainloop()

您还需要绑定相应的KeyRelease-*事件。 例如,添加到您的代码中:

def up(event):
   ...
   myButton1.configure(bg='yellow')

def up_release(event):
   myButton1.configure(bg='grey')

...
window.bind("<KeyRelease-Up>", up_release)

有关更多详细信息,请参见TkInter 按键、按键释放事件以及如何重置 python tkinter 按钮的背景颜色? 恢复以前的颜色(而不是灰色)。

  • 定义状态 label myLabel外部回调 function
  • 定义一个字典来链接键名和相应的按钮
  • <KeyPress><KeyRelease>绑定到相应的回调,并更新相应按钮的背景颜色和回调中myLabel的文本
from tkinter import *

window = Tk()
window.title("Arrow Keys")
window.geometry('820x640')
width = 820
height = 640

myButton1 = Button(window, text="    UP   ", activebackground='red')
myButton1.place(x= 387, y=10)
myButton2 = Button(window, text="DOWN", activebackground='red')
myButton2.place(x= 399, y= 60)
#myButton2.pack(pady=60) ### don't call pack() after using place()
myButton3 = Button(window, text=" LEFT ", activebackground='red')
myButton3.place(x= 345, y=35)
myButton4 = Button(window, text="RIGHT", activebackground='red')
myButton4.place(x= 435, y= 35)

# save the background color or button
btn_bg = myButton1.cget("bg")

myLabel = Label(window)
myLabel.place(x=50, y=50)

keys = {"Up": myButton1, "Down": myButton2, "Left": myButton3, "Right": myButton4}

def on_key_press(event):
    if event.keysym in keys:
        keys[event.keysym].config(bg="red")
        myLabel.config(text=event.keysym)

def on_key_release(event):
    if event.keysym in keys:
        keys[event.keysym].config(bg=btn_bg)
        myLabel.config(text="")

window.bind("<KeyPress>", on_key_press)
window.bind("<KeyRelease>", on_key_release)

window.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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