How to activate tkinter buttons with keyboard? - python

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

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.

Related

Problems while drawing straight line and dragging in Tkinter canvas

So, I'm trying to draw vertical lines in canvas on the click of the button "line".
These are the problems and my requirements:
When i try click on the line drawn to drag it to a position, it repels away from the mouse cursor but moves in the correct direction. What do i do to prevent this?
On subsequent clicks on the "line" button, i want a new line to be drawn (every time i click) while the original lines stays in the canvas unmoved.
The latest line is the only one which can be dragged. All other lines should be static.
I want coordinates of all these drawn lines. How do i get these?
This is the code i've written:
from tkinter import *
import tkinter
root = Tk()
canvas = tkinter.Canvas(root, width = 480,height = 600)
canvas.pack()
def draw_lines():
canvas.create_line(300, 35, 300, 200, dash=(4, 2))
def drag(event):
event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)
canvas.bind("<B1-Motion>", drag)
btn1 = Button(root, text = 'line', bd = '5',command = draw_lines)
btn2 = Button(root, text = 'Close', bd = '5',command = root.destroy)
btn1.pack(side = 'top')
btn2.pack(side = 'top')
canvas.mainloop()
please help!!!!
Using Python 3.11.0rc1.
I added:
geometry. so it will not resize when dragging.
Canvas. You have to play around with height set to 800
I removed bd=5. You can suit yourself. Don't use quote.
I removed Quotes for this btn1.pack(side=TOP)
At last canvas.pack() always next to mainloop()
Here is the code re-worked:
from tkinter import *
root = Tk()
root.geometry('400x650')
canvas = Canvas(root, width=480, height=600)
def draw_lines():
canvas.create_line(300, 35, 300, 200, dash=(4, 2))
def drag(event):
event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)
canvas.bind("<B1-Motion>", drag)
btn1 = Button(root, text='line', command=draw_lines)
btn2 = Button(root, text= 'Close', command=root.destroy)
btn1.pack(side=TOP)
btn2.pack(side=TOP)
canvas.pack()
canvas.mainloop()
Result output:

How to delete popup window in tkinter?

I have a sequence of pop up windows. I intended to close the window once i have completed the desired task. I am using a "askokcancel" button to get users confirmation whether the activity has completed. The problem is, every time the user presses ok, the focus goes back to the main starting window and rest of the pop up windows goes to the background while staying active. I want to either close the pop up windows or keep the focus to the second last window. Below is my code:
import tkinter as tk
from tkinter import ttk, StringVar, messagebox
from tkinter.filedialog import askopenfilename
from mytest import *
from tkinter import *
class myclass:
def __init__(self, master):
self.master = master
self.frame1 = tk.Frame(self.master)
self.button1 = tk.Button(self.frame1, text = 'select me first', width = 25, command = self.buttonFunc)
self.button1.pack()
self.quitButton = tk.Button(self.frame1, text = 'Quit', width = 25, command = self.close_windows1)
self.quitButton.pack()
self.frame1.pack()
self.master.geometry("200x200+60+60")
def buttonFunc(self):
self.top = tk.Toplevel(self.master)
self.button2 = tk.Button(self.top,text="Select second",command=self.anotherButtonFunc)
self.button2.pack()
self.quitButton = tk.Button(self.top, text = 'Quit', width = 25, command = self.close_windows2)
self.quitButton.pack()
self.master.geometry("200x200+60+60")
def anotherButtonFunc(self):
self.top2 = tk.Toplevel(self.top)
self.newClass = myClassExt(self.top2)
def close_windows1(self):
self.master.destroy()
def close_windows2(self):
self.top.destroy()
class myClassExt():
def __init__(self, top2):
self.top3 = top2
self.frame2 = tk.Frame(self.top3)
self.button3 = tk.Button(self.frame2, text = 'select me third', width = 25, command = self.buttonFunc)
self.button3.pack()
self.quitButton = tk.Button(self.frame2, text = 'Quit', width = 25, command = self.close_windows4)
self.quitButton.pack()
self.frame2.pack()
self.top3.geometry("200x200+60+60")
def buttonFunc(self):
ok = messagebox.askokcancel(message='Press OK to Confirm?')
if not ok:
pass
else:
messagebox.showinfo("Success","Well done")
self.close_windows4()
def close_windows4(self):
self.top3.destroy()
if __name__ == "__main__":
root = tk.Tk()
myclass = myclass(root)
root.mainloop()
From this made up example, i somehow want to either close window number 2 after user presses OK or keep the focus on window 2 rather than window 1. Please guide
There is no way to close a message box, although you can easily make your own. You just have to make a new tkinter window, and set an image, title, and text, then add a close button, and return the tk window. I made a function like this myself, for this very reason. Here is the function:
def mymessage(title, text, spacing = 25, buttonText = "Close", image = None):
tk2 = Tk()
tk2.resizable(0, 0)
tk2.title(title)
if image != None:
image = Label(tk2, image = PhotoImage(file = image))
image.pack()
spacer = Frame(tk2, relief = FLAT, bd = 0, width = 200, height = 25)
spacer.pack()
label = Label(tk2, text = text)
label.pack()
button = Button(tk2, text = buttonText, width = 5, height = 1, command = tk2.destroy)
button.pack()
return tk2
After calling the function, it returns the tk window, for easy destruction.

Python 3.5: Print Canvas Text

Could anyone share with me how to print the text of the text widget added to a Canvas object? In the code below, I want the system return the value of "hello" when mouse on the text, however, it turns out giving me "1". Don't know why. Could anyone help me?
Many many thanks!!!
import tkinter
from tkinter import *
def show_text(event):
print (canvas.text)
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
mainloop()
According to the canvas docs:
You can display one or more lines of text on a canvas C by creating a
text object:
id = C.create_text(x, y, option, ...)
This returns the object ID of the text object on canvas C.
Now, you gotta modify the code something like this:
import tkinter
from tkinter import *
def show_text(event):
print (canvas.itemcget(obj_id, 'text'))
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
obj_id = canvas.create_text(20, 30, text="hello")
mainloop()
Follow up (see the documentation for Label.config:
import tkinter
from tkinter import *
from tkinter import ttk
def show_text(event):
print (canvas.itemcget(canvas.text, 'text'))
#The command of writing text 'hello' in sch_Label to replace the text 'the info shows here'
sch_Label.config(text = 'hello!')
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
pad1 = ttk.Notebook(master)
pad1.pack(side=RIGHT, expand=1, fill="both")
tab1 = Frame(pad1)
pad1.add(tab1, text = "Schedule")
pad1.pack(side=RIGHT)
sch_Label = ttk.Label(tab1, text='The info shows here')
sch_Label.pack(side="top", anchor="w")
mainloop()

How to make a flashing text box in tkinter?

So my computing class are making a xmas card in python, and for one of the bits there is going to be a text box with a message, but how do I make the background alternate from green and red ?
If someone would be able to help that would be amazing :)
from tkinter import *
root = Tk()
root.title("Xmas Message")
#command for the button
def test_com():
#removing the button
act_btn.grid_remove()
#adding the textbox for the message
msg_box = Text(root, height = 1, width = 30)
msg_box.grid(row=0, column=0)
#adding the message
msg_box.insert(END, "Happy Xmas")
#changing the background to green
msg_box.config(background="green")
#changing the background to red
msg_box.config(background="red")
root.after(250, test_com)
#button for activating the command
act_btn = Button(root, text = "1", command = test_com)
act_btn.grid(row=0, column=0)
root.mainloop()
Create a change_color callback that alternates the text box's color, and uses after to call itself a second in the future.
Sample implementation:
from tkinter import *
def change_color():
current_color = box.cget("background")
next_color = "green" if current_color == "red" else "red"
box.config(background=next_color)
root.after(1000, change_color)
root = Tk()
box = Text(root, background="green")
box.pack()
change_color()
root.mainloop()

Image in tkinter window by clicking on button

I need help about this program, this program should open image in new tkinter window by clicking on button, but it doesn't it just opens new window without image.
Where is the problem?
Using: python 3.3 and tkinter
This is program:
import sys
from tkinter import *
def button1():
novi = Toplevel()
canvas = Canvas(novi, width = 300, height = 200)
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'image.gif')
canvas.create_image(50, 10, visual = gif1, anchor = NW)
mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()
mGui.mainloop()
create_image needs a image argument, not visual to use the image, so instead of visual = gif1, you need image = gif1. The next problem is that you need to store the gif1 reference somewhere or else it'll get garbage collected and tkinter won't be able to use it anymore.
So something like this:
import sys
from tkinter import * #or Tkinter if you're on Python2.7
def button1():
novi = Toplevel()
canvas = Canvas(novi, width = 300, height = 200)
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'image.gif')
#image not visual
canvas.create_image(50, 10, image = gif1, anchor = NW)
#assigned the gif1 to the canvas object
canvas.gif1 = gif1
mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()
mGui.mainloop()
It's also probably not a good idea to name your Button the same name as the function button1, that'll just cause confusion later on.
from tkinter import *
root = Tk()
root.title("Creater window")
def Img():
r = Toplevel()
r.title("My image")
canvas = Canvas(r, height=600, width=600)
canvas.pack()
my_image = PhotoImage(file='C:\\Python34\\Lib\idlelib\\Icons\\Baba.gif', master= root)
canvas.create_image(0, 0, anchor=NW, image=my_image)
r.mainloop()
btn = Button(root, text = "Click Here to see creator Image", command = Img)
btn.grid(row = 0, column = 0)
root.mainloop()

Categories