Scorp Y
Scorp Y

Reputation: 51

How to activate tkinter buttons with keyboard?

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?

Thanks for the support Have a happy day

Here is the code:

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

WRITTEN IN PYTHON BY ALAN ABUNDIS

Upvotes: 3

Views: 6170

Answers (1)

Ayu_Sh_Arma
Ayu_Sh_Arma

Reputation: 80

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)

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

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

And now to define function:

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

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.

Upvotes: 3

Related Questions