Add event for 'windows' button in tkinter? - python

My Code:
from tkinter import*
root = Tk()
root.geometry("500x500")
def moti(event):
root.destroy()
root.bind("<Window>",moti)
root.mainloop()
I want to bind this key
So,how can I bind This key in windows?Thank you!

From a practical example, I was able to find the windows key is called as <Win_L>(for the left key) <Win_R> for the right one), you can find that out yourself by using this code:
import tkinter as tk
root = tk.Tk()
def event(e):
print(e.keysym)
root.bind('<Key>',event)
root.mainloop()
This will print the key name once the window has focus and you press on it.
So TL;DR: The key name for the windows key is <Win_L>. Also for reference read keysyms manual page - Tk-built-in-commands
w.bind('<Win_L>',callback)
Note: While on Windows systems you can use <Win_L>, on a ubuntu system it would be <Super_L>. So a safe method would be:
from tkinter import *
root = Tk()
def event(e):
print(f'You just clicked: {e.keysym}')
try:
root.bind('<Win_L>',event)
except TclError:
root.bind('<Super_L>',event)
root.mainloop()

Related

How will I make a tk window which cannot be minimized in Python Tkinter?

I tried win.overrideredirect(True) it didn't work...
My Code goes like this:
from tkinter import *
win = Tk()
win.resizable(0,0)
win.wm_protocol("WM_SAVE_YOURSELF", lambda: print("On exit"))
Label(win, text="Tk Window").pack()
win.mainloop()
Specs:
Python 3.9.6 [Latest],
Pip 21.1.3,
OS: Windows 10 Home
I want to make the minimize button to be disabled...
Please help
The thing #N1CK145 posted didn't work for me but I am guessing that he/she tried to do this:
import Tkinter as tk
root = tk.Tk()
root.attributes("-toolwindow", True)
root.mainloop()
If you want to know more attribute options look here
try resizeable function like this :
win= Tk()
win.geometry("750x250")
win.resizable(False, False)
Found this here:
import Tkinter as tk
root= tk.Tk()
root.title("wm min/max")
# this removes the maximize button
root.resizable(0,0)
# # if on MS Windows, this might do the trick,
# # but I wouldn't know:
# root.attributes(toolwindow=1)
# # for no window manager decorations at all:
# root.overrideredirect(1)
# # useful for something like a splash screen
root.mainloop()

Change right click event of tkinter command

I want to detect the right click event on tkinter Menu command.
Consider code below.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
menu_button = ttk.Menubutton(root, text="MENU")
menu_button.grid()
m = tk.Menu(menu_button, tearoff=False, activeborderwidth=0)
menu_button["menu"] = m # To avoid garbage collection
m.add_command(label="an option", command=lambda: print("option1"))
m.add_command(label="another option", command=lambda: print("option2"))
root.mainloop()
When I click an option or another option, the commands are called as expected. But want I want to do is catch right click event. Can anyone knows that how can I detect it?
use button.bind("<Button-3>", event). Consider this code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
button = tk.Button(root, text='right click this')
button.pack()
button.bind("<Button-3>", lambda e: print('You right clicked'))
root.mainloop()

Tkinter how to bind to shift+tab

I'm trying to bind the SHIFT+TAB keys, but I can't seem to get it to work. The widget I'm binding to is an Entry widget.
I've tried binding the keys with widget.bind('<Shift_Tab>', func), but I get an error message saying:
File "/usr/lib64/python3.8/tkinter/init.py", line 1337, in
_bind self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "Shift_Tab"
Update
I'm still having a problem detecting SHIFT+TAB. Here is my test code. My OS is Linux. The tab key works, just not SHIFT+TAB. Seems like a simple problem to solve, so I must be going about it wrong?
I'm trying to tab between columns in a Treeview that I have overlaid widgets on a row to simulate inline editing. There can be only one active widget on a line. I keep track of what column I'm in and when the user presses SHIFT+TAB or TAB, I remove the current widget and display a new widget in the corresponding column.
Here is a link to the complete project:
The project is in one file and has no imports.
The code below is my attempt and it doesn't work.
import tkinter as tk
import tkinter.ttk as ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.title('Default Demo')
self.geometry('420x200')
wdg = ttk.Entry(self)
wdg.grid()
def tab(_):
print('Tab pressed.')
def shift_tab(_):
print('Shift tab pressed.')
wdg.bind('<Tab>', tab)
wdg.bind('<Control-ISO_Left_Tab>', shift_tab)
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()
The following code (in python 2.7.6) should make it clear:
I hope this reference works for you
from Tkinter import *
def key(event=None):
print 'You pressed Ctrl+Shift+Tab'
root = Tk()
frame = Frame(root, width=100, height=100)
frame.focus_set()
frame.bind('<Control-Shift-KeyPress-Tab>', key)
frame.pack()
root.mainloop()
EDIT: The above works well for Windows and Mac. For Linux, use
'<Control-ISO_Left_Tab>'.
Not a direct answer and too long for a comment.
You can solve your question by yourself with a simple trick, bind <Key> to a function, and print the key event argument passed to the bind function where you can see which key is pressed or not. Try multiple combinations of keys to see what is the state and what is their keysym or keycode.
import tkinter as tk
def key_press(evt):
print(evt)
root = tk.Tk()
root.bind("<Key>", key_press)
root.mainloop()
It will output the following for pressing SHIFT + TAB combo on macOS.
<KeyPress event state=Shift keysym=Tab keycode=3145753 char='\x19' x=-5 y=-50>
Where,
state=Shift means a key event's state is on SHIFT.
keysym=Tab means tab key is pressed. If we just press SHIFT, the keysym will be Shift_L or Shift_R (shows Shift_L for both shift keys on mac).
keycode is an unique code for each key even for different key combos for example keycode for Left Shift is 131330 and keycode for TAB is 3145737 but when SHIFT + TAB is pressed the code is not the same to either, it is 3145753. (I'm not sure if these are the same code for every os but one can figure it out by printing them to the console)
Also, see all the event attributes.
Though bind '<Shift-Tab>' key combination works well on Mac, it can also be used like so...
def key_press(evt):
if evt.keycode==3145753:
print('Shift+Tab is pressed')
Here is my solution for Linux users that want to bind Shift+Tab.
def press(e):
print('Shift+Tab is pressed')
widget.bind('<ISO_Left_Tab>',press)

cmd + a not working in tkinter entry

I've being building a basic UI using Tkinter, and I noticed that cmd + a (or Select all command) is not enabled.
How do I enable all the shortcuts in tkinter especially for entry text field.
This is my code :
entry1 = ttk.Entry(root, width = 60)
entry1.pack()
If tkinter doesn't define the shorcuts you want you can define your own by binding keyboard events.
import tkinter as tk
import tkinter.ttk as ttk
def callback(ev):
ev.widget.select_range(0, 'end')
root = tk.Tk()
entry = ttk.Entry(root)
entry.pack()
entry.bind('<Command-a>', callback)
root.mainloop()
I think Command is the correct prefix for the cmd key but I don't have a mac to test. In windows it binds to the control key.
#Goyo already answered your question. I want to share my contribution as I do not see interest in selecting the text of the Entry widget's text and not doing anything else with it. So I am going to provide you a dirty MCVE to show how you are going to use the selected text: a) either you will delete it or b) you will copy it.
For a), the following function will do the job:
def select_text_or_select_and_copy_text(e):
e.widget.select_range(0, 'end')
It will work under the condition you bind the corresponding events described by the function's name to the entry widget:
entry.bind('<Control-a>', select_text_or_select_and_copy_text)
entry.bind('<Control-c>', select_text_or_select_and_copy_text)
For b), you can use this function:
def delete_text(e):
e.widget.delete('0', 'end')
And bind the Delete event to the entry widget:
entry.bind('<Delete>', delete_text)
I tried this MCVE on Ubuntu and it works:
import tkinter as tk
import tkinter.ttk as ttk
def select_text_or_select_and_copy_text(e):
e.widget.select_range(0, 'end')
def delete_text(e):
e.widget.delete('0', 'end')
root = tk.Tk()
entry = ttk.Entry(root)
entry.pack()
entry.bind('<Control-a>', select_text_or_select_and_copy_text)
entry.bind('<Control-c>', select_text_or_select_and_copy_text)
entry.bind('<Delete>', delete_text)
root.mainloop()

Python tkinter simpledialog. How to bind a key to the OK button in simpledialog

def prompt_new_name(self):
new_name = simpledialog.askstring("Name Change", "New name")
if new_name is not None:
self.request_name_change(new_name)
I want to bind enter key on the keypad to the OK button in the simpledialog askstrinig prompt. (realized later normal enter key is already bound, but I need both enter keys to be bound)
I know how to bind enter key to a widget using bind function. However, to do that I need a reference to the widget.
For this case, I don't have the reference to the widget since I am calling askstring fuction on simpledialog without making the widget. I am wondering how I can achieve what I want.
SimpleDialog is "simple". Create own dialog (using TopLevel widget) if you need something different.
Or see SimpleDialog source code to recreate askstring
https://fossies.org/dox/Python-3.5.0/simpledialog_8py_source.html
import tkinter as tk
import tkinter.simpledialog
class My_QueryString(tkinter.simpledialog._QueryString):
def body(self, master):
self.bind('<KP_Enter>', self.ok) # KeyPad Enter
super().body(master)
def myaskstring(title, prompt, **kw):
d = My_QueryString(title, prompt, **kw)
return d.result
#---------------------------------------------------------
root = tk.Tk()
new_name = myaskstring("Name Change", "New name")
if new_name:
print(new_name)
root.mainloop()

Categories

Resources