python - 如何用键盘激活 tkinter 按钮?

标签 python tkinter

我正在制作一个音乐应用程序,一个使用 GUI(图形用户界面)演奏鼓的应用程序。所以我已经为每个鼓标记了按钮,并且我已经在 Canvas 上绘制了鼓组,但我不知道如何使用计算机键盘激活按钮,这可能吗?

感谢支持 祝你有愉快的一天

这是代码:

##import libraries
from Tkinter import *
from winsound import *
import os
import ttk

##Initialize
root = Tk()
root.geometry('{}x{}'.format(938, 600))
canvas = Canvas(root, width = 938, height = 505, bg = 'white')
canvas.pack()
label = ttk.Label(root, text ="Hello my name is Scorp welcome to this drums 
app")
label.pack()
label.config(foreground ='black')
label.config(font = ('arial',15, 'bold'))
##PhotoImage(file ="g1.gif")
logo =PhotoImage(file ="drums1.gif")
imageFinal = canvas.create_image(480, 260, image = logo)


##logo =PhotoImage(file ="drums.gif")
##imageFinal = canvas.create_image(530, 80, image = logo)


def move():
    canvas.move(imageFinal, 10, 10 )
    canvas.move(label, 10, 10) 
    canvas.update()

def play1():
    os.system('hi_hat.wav')

##define buttons
button = Button(text = 'move', height = 2, width = 4, command = move)
button.place(x=556, y=550)
button1 = Button(text = 'Hi-Hat', height = 2, width = 10, command = play1)
button1.place(x=20, y=240)
root.mainloop()

由 ALAN ABUNDIS 用 Python 编写

最佳答案

您可以将键盘按键与 GUI 按钮功能绑定(bind),这样每当您按下选定的键盘按键时,该功能就会访问。

首先您必须创建按钮:

btn = Button(text = 'move', height = 2, width = 4, command = move) button.place(x=556, y=550)

现在用键绑定(bind)它(例如shift+z):

btn.bind("<Shift-Z>", move)

现在定义函数:

def move(event=' '): canvas.move(imageFinal, 10, 10 ) canvas.move(label, 10, 10) canvas.update()

您必须为您使用键绑定(bind)的函数提供一个“事件”参数。我已将事件的默认值设置为空字符串,因此每当您使用鼠标按下屏幕上的按钮时,它都不会给出错误。

关于python - 如何用键盘激活 tkinter 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518052/

相关文章:

python - 尽管更改了 pyCharm python 解释器路径,但仍无法将 pandas 导入 pycharm 解释器

python - 如何授予模块对非 Python 文件的访问权限

python - 将多个网页抓取到单个 csv 中

python - 将 classification_report 的准确度返回到列表中

python - Flask-Restful:通过 POST 请求将列表传递到 MongoDB

python - 使用 Tkinter 的全屏窗口

python-3.x - Control-Shift-Tab 的 Tkinter 键绑定(bind)

python gui 事件乱序

python - 如何通过标签更改Treeview中项目的背景/前景?

python - Tkinter ttk 背景样式的自定义未显示