cmd + a not working in tkinter entry - python

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

Related

Add event for 'windows' button in tkinter?

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

Checkbutton on tkinter retains it's value no matter what

I'm trying to get the value from Checkbutton on tkinter but it retains the original value. I have tried what people say on countless forums including this one but nothing works, it just retains the value i give it with var.set(True) or var.set(False). This chechbutton is on a pop up window btw, but it's not global, it's just defined on said window. this is my code:
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry('500x500')
var = tk.BooleanVar()
var.set(False)
startup = tk.Checkbutton(root, variable=var, onvalue=True, offvalue=False , text = "test")
when ver i use var.get() i get the initial value. help me plz :( Thanks in advice.
The reason is because Checkbutton requires a callback function to change the state of the button.
def toggle(button):
if button.get() is True:
button.set(True)
else:
button.set(False)
The you would use the callback function in the instantiation of the Checkbutton
startup = tk.Checkbutton(root, variable=var, text = "test",
command=lambda button=var: toggle(button))

Trouble With Tkinter in Python [duplicate]

I'm trying to make a simple outline for a gui, and I'm getting the warning
"variable" May be undefined or defined from star imports: tkinter for all of my variables.
Here is my code:
from tkinter import *
class myApp :
def __init__(self, gui,) :
self.root = gui
self.bframe = Frame(self.root) # Create a container Frame at bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Item ID") # Create the Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create the Entry box
self.xentry.pack(side=LEFT)
self.xentry.bind('<Return>', self.showStockItem)
self.xentry.focus_set() # Set focus in the Entry box
self.xopen = Button(self.root, text="Show", command=self.showStockItem) # Create the open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create the quit Button
self.xquit.pack(side=BOTTOM)
return
gui = Tk()
gui.title("Travel")
app = myApp(gui)
gui.mainloop()
from tkinter import *
In this line, you import everything from tkinter. This is not recommended, so linter will warn you. But if you really want to do this, it's OK, just ignore it.
To be better, you should explicitly import what you need. For example:
from tkinter import Tk, Label, Frame, Entry, Button
Consider using:
import tkinter as tk
and then, prefix all your calls like:
root = tk.Tk()
or,
variableName.pack(side = tk.LEFT)
and so on...

How to assign a button click into a variable on tkinter

I want to create a tkinter window, where it will appear the files of a folder as a dropdown menu and a Select button, such that when I select an element from the previous list the full path will be saved into a new variable. Apparently, I need to give an appropriate command.
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command= ?)
w.pack()
root.mainloop()
I think what you need here is actually a binding. Button not required.
Here is an example that will list everything in your selected directory and then when you click on it in the Combo Box it will print out its selection.
Update, added directory and file name combining to get new full path:
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
new_full_path = ""
root = Tk()
# we use StringVar() to track the currently selected string in the combobox
current_selected_filepath = StringVar()
b = ttk.Combobox(master=root, values=current_selected_filepath)
function used to read the current StringVar of b
def update_file_path(event=None):
global b, new_full_path
# combining the directory path with the file name to get full path.
# keep in mind if you are going to be changing directories then
# you need to use one of FileDialogs methods to update your directory
new_full_path = "{}{}".format(indir, b.get())
print(new_full_path)
# here we set all the values of the combobox with names of the files in the dir of choice
b['values'] = os.listdir(indir)
# we now bind the Cobobox Select event to call our print function that reads to StringVar
b.bind("<<ComboboxSelected>>", update_file_path)
b.pack()
# we can also use a button to call the same function to print the StringVar
Button(root, text="Print selected", command=update_file_path).pack()
root.mainloop()
Try something like this:
w = Button(master=root, text='Select', command=do_something)
def do_something():
#do something
In the function do_something you create what you need to get the full path. You can also pass vars into the command.
get()
Returns the current value of the combobox.(https://docs.python.org/3.2/library/tkinter.ttk.html)
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
#This function will be invoked with selected combobox value when click on the button
def func_(data_selected_from_combo):
full_path = "{}/{}".format(indir, data_selected_from_combo)
print full_path
# Use this full path to do further
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command=lambda: func_(b.get()))
w.pack()
root.mainloop()

How to use a <ComboboxSelected> virtual event with tkinter

I am using a tkk.Combobox themed widget in Python 3.5.2. I want an action to happen when a value is selected.
In the Python docs, it says:
The combobox widgets generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.
Here on the Stack, there are a number of answers (1, 2, etc) that show how to bind the event:
cbox.bind("<<ComboboxSelected>>", function)
However, I can't make it work. Here's a very simple example demonstrating my non-functioning attempt:
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)
cbox.bind("<<ComboboxSelected>>", print("Selected!"))
tkwindow.mainloop()
I get one instance of "Selected!" immediately when I run this code, even without clicking anything. But nothing happens when I actually select something in the combobox.
I'm using IDLE in Windows 7, in case it makes a difference.
What am I missing?
The problem is not with the event <<ComboboxSelected>>, but the fact that bind function requires a callback as second argument.
When you do:
cbox.bind("<<ComboboxSelected>>", print("Selected!"))
you're basically assigning the result of the call to print("Selected!") as callback.
To solve your problem, you can either simply assign a function object to call whenever the event occurs (option 1, which is the advisable one) or use lambda functions (option 2).
Here's the option 1:
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)
def callback(eventObject):
print(eventObject)
cbox.bind("<<ComboboxSelected>>", callback)
tkwindow.mainloop()
Note the absence of () after callback in: cbox.bind("<<ComboboxSelected>>", callback).
Here's option 2:
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)
cbox.bind("<<ComboboxSelected>>", lambda _ : print("Selected!"))
tkwindow.mainloop()
Check what are lambda functions and how to use them!
Check this article to know more about events and bindings:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
Thanks you for the posts. I tried *args and it workes with bind and button as well:
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
def callback(*args):
print(eventObject)
cbox.bind("<<ComboboxSelected>>", callback)
btn = ttk.Button(tkwindow, text="Call Callback", command=callback);
tkwindow.mainloop()

Categories

Resources