Tkinter focus on Entry when script run - python

I am using tkinter to make a small user input sort of thing.
I couldn't find how to set focus to an Entry box when the script is run.
I.e. When the window opens, the first thing that automatically gets focus is the Entry box. set_focus() or focus() doesn't seem to work.
Here is my code:
root = Tk()
v = StringVar()
text = Entry(root,
textvariable=v).grid(column=0,row=0)
text.focus_set()
root.mainloop()

A geometry manager (.grid(), or .pack(), etc...) returns None. You must not use it on the same line as the assignment to a variable:
Your code was trying to call .focus_set() on a variable text whose value was set to None.
Further, the correct method to set the focus to a widget is focus_set(), not set_focus().
root = Tk()
v = StringVar()
text = Entry(root, textvariable=v)
text.grid(column=0, row=0)
text. focus_set()
root.mainloop()

Related

Remove tkinter widget called using .place

I am working on an app using Tkinter and I have a small question.
For example, I have a label placed like this:
Label = Label(root, text="Hello").place(x=5, y=5)
Is there any way to hide the label when a button is pressed or when a function is called?
Any help will be appreciated
Thanks!
You should simply never chain .place() or any other geometry manager to the widget creator. It returns None.
lbl_name = Label(root, text="Hello")
lbl_name.place(x=5, y=5)
Now you can handle lbl_name as a label object. To hide it you can use:
lbl_name.place_forget()
Unfortunately, now its gone. Therefore, first save the place properties:
lbl_name = Label(root, text="Hello")
lbl_name.place(x=5, y=5)
lbl_name.saved = lbl_name.place_info()
You can now show it again with:
lbl_name.place(lbl_name.saved)
Note: You can print lbl_name.saved. It is a dictionary with all place-properties of the lbl_name Label object.

how to copy a string that appears on tkinter GUI

i have a password generator script that works fine, problem is, i present the password in the GUI in a label and it doesn't give me the option to copy it so i can put the password where i want it, how can i print the password to the GUI so i can copy it after, is there a better way than label?
I am using the function
tk.Label(root,text=k).grid(row=1)
k being the variable where the password is stored
Alternately if there is some python function that enables me to just straight up copy the contents of k to the clipboard that might be even better, thanks
The simplest solution is to use an Entry widget with the state set to "readonly".
Example:
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(root)
entry.pack(side="top", padx=20, pady=20)
# insert the password
entry.insert(0, "SuperSecretPassw0rd!")
# configure the entry to readonly
entry.configure(state="readonly")
root.mainloop()
You can also automatically add it to the clipboard with the clipboard_clear and clipboard_append methods:
root.clipboard_clear()
root.clipboard_append(entry.get())
If I understand your problem correctly, you want to get or set a value in a TK gui? Instead of using a Label, I would use an Entry, and I would use one of the TK variable classes (such as StringVar) for k, which have get and set methods
here's a example of a script I use to get and set text values in a TK widget:
frame = tk.Frame(master)
frame.pack()
filepath = tk.StringVar()
filepath.set("/Volumes/data/data/test_data/")
fileentry = tk.Entry(frame, textvariable=filepath, width=125)
fileentry.pack()
if something:
a = filepath.get()
reference to TK variable classes: https://effbot.org/tkinterbook/variable.htm

Tkinter Entry returns float values regardless of input

I have some pretty simple code right now that I am having issues with.
root = Tk()
label1 = Label(root, text ="Enter String:")
userInputString = Entry(root)
label1.pack()
userInputString.pack()
submit = Button(root,text = "Submit", command = root.destroy)
submit.pack(side =BOTTOM)
root.mainloop()
print(userInputString)
When I run the code everything operates as I would expect except
print(userInputString)
for an input asdf in the Entry print will return something like 0.9355325
But it will never be the same value back to back always random.
I am using python 3.5 and Eclipse Neon on a Windows 7 Machine.
Ultimately the goal is to accept a string from the user in the box that pops up and then be able to use that value as string later on. For example, it might be a file path that needs to be modified or opened.
Is Entry not the correct widget I should be using for this? Is there something inherently wrong with the code here? I am new to python and don't have a lot of strong programming experience so I am not even certain that this is set up right to receive a string.
Thanks in advance if anyone has any ideas.
There are two things wrong with your print statement. First, you print the widget, not the text in the widget. print(widget) prints str(widget), which is the tk pathname of the widget. The '.' represents the root window. The integer that follows is a number that tkinter assigned as the name of the widget. In current 3.6, it would instead be 'entry', so you would see ".entry".
Second, you try to print the widget text after you destroy the widget. After root.destroy, the python tkinter wrapper still exists, but the tk widget that it wrapped is gone. The following works on 3.6, Win10.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Enter String:")
entry = tk.Entry(root)
def print_entry(event=None):
print(entry.get())
entry.bind('<Key-Return>', print_entry)
entry.focus_set()
submit = tk.Button(root, text="Submit", command=print_entry)
label.pack()
entry.pack()
submit.pack()
root.mainloop()
Bonus 1: I set the focus to the entry box so one can start typing without tabbing to the box or clicking on it.
Bonus 2: I bound the key to the submit function so one can submit without using the mouse. Note that the command then requires an 'event' parameter, but it must default to None to use it with the button.
The NMT Reference, which I use constantly, is fairly complete and mostly correct.

Get TkInter to display user input?

I am fairly new to TkInter and GUI in python (but I have experience with python in general). I was working on a GUI in TkInter and want to have users enter their name and have TkInter display there name when they click the button. Here is my code so far:
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.pack()
separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)
Label(text=callback).pack()
mainloop()
Users will enter their name in the Entry (or e) and I want to display e in the label widget. Any ideas on how I can do this? Thanks.
At the top (below the imports), define name as a StringVar:
name = StringVar()
In the function callback change the content to be:
def callback():
name.set(e.get())
And finally, change your Label widget to:
Label(master, textvariable=name)
So what I have done is created a special object with which when we change its value, the value of all references to it will change also. We can then set our function to change the value to update it globally- and we finish by utilizing this capability by putting this variable as the text attribute in our Label.
Note: I also added the parent argument to your Label. Without it, it wouldn't show up at all.

How do I prepopulate a text field with suggested text in Tkinter?

I'm trying to prepopulate a text field based on the most recent entry. As this is not a Listbox, I don't see how to do it, and I'm not seeing any examples on the web. Thanks.
Update. I've managed to find a partial way of doing this. Still wondering, is it possible to supply suggested text in Tkinter which fades when the text box is clicked?
from Tkinter import *
app = Tk()
app.title("GUI Example")
app.geometry('560x460+200+200')
x = Text(app)
x.insert(END, "Before")
x.pack()
def replace():
x.delete(1.0, END)
x.insert(END, "After")
abutton = Button(app, text="Click me", command=replace)
abutton.pack()
app.mainloop()
Well, I personally don't know of any options to do this (any answers giving one will easily trump this one).
However, you can closely mimic this behavior with a little coding. Namely, you can bind the textbox to a function that will insert/remove the default text for you.
Below is a simple script to demonstrate:
import Tkinter as tk
tk.Tk()
textbox = tk.Text(height=10, width=10)
textbox.insert(tk.END, "Default")
textbox.pack()
# This is for demonstration purposes
tk.Text(height=10, width=10).pack()
def default(event):
current = textbox.get("1.0", tk.END)
if current == "Default\n":
textbox.delete("1.0", tk.END)
elif current == "\n":
textbox.insert("1.0", "Default")
textbox.bind("<FocusIn>", default)
textbox.bind("<FocusOut>", default)
tk.mainloop()
Notice how:
When you click in the top textbox, the default text disappears.
When you click in the bottom textbox, the top one loses focus and the default text reappears.
This behavior will only occur if there is nothing in the top textbox.

Categories

Resources