如何用键盘激活 tkinter 按钮? [英] How to activate tkinter buttons with keyboard?

查看:76
本文介绍了如何用键盘激活 tkinter 按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个音乐应用程序,一个使用 GUI(图形用户界面)演奏鼓的应用程序.所以我已经为每块鼓贴上了标签,我的架子鼓已经画在画布上,但我不知道如何用我的电脑键盘激活按钮,这可能吗?

Im making a musical app, an application for playing drums with GUI(graphical user interface). So i already have the buttons labeled for every piece of the drums and i have my drum kit already drawn in my canvas, but i dont know how to activate the buttons with my computer keyboard, is it possible?

感谢支持祝你天天开心

代码如下:

##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()

由艾伦·阿邦迪斯用 Python 编写

推荐答案

您可以将键盘按键与 GUI 按钮功能绑定,这样无论您何时按下选定的键盘按键,该功能都会访问.

You can bind your keyboard keys with your GUI button functions so whenever you you press the selected keyboard key the function will access.

首先你必须创建你的按钮:

First you have to create your button:

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

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

Now to bind it with a key(for example shift+z):

btn.bind("", move)

现在定义函数:

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

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

You have to give a 'event' argument to your function which you are binding with a key. I have set the default value of event to a empty string so whenever you press the button on screen using mouse it wont give you an error.

这篇关于如何用键盘激活 tkinter 按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆