Python 'len' function [duplicate] - python

I am creating an application and I want to use the entered values in the GUI Entry widget.
How do I get the entered input from a Tkinter Entry widget?
root = Tk()
...
entry = Entry(root)
entry.pack()
root.mainloop()

You need to do two things: keep a reference to the widget, and then use the get() method to get the string.
Here's an example:
self.entry = Entry(...)
...
print("the text is", self.entry.get())

Here's an example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
w = SampleApp()
w.mainloop()

First declare a variable of required type. For example an integer:
var = IntVar()
Then:
entry = Entry(root, textvariable=var)
entry.pack()
user_input = var.get()
root.mainloop()
Hope this helps.

Related

Problem with Tkinter and creating a new window

I am quite new with Tkinter and am trying to create a new window using this script while keeping the current window but i am get the error
_init_() missing 1 required positional argument: 'parent'. I am not really sure what the reason is but I am assuming that the command function for my button isn't working the way I want it.
The script currently looks something like this:
from tkinter import simpledialog
from tkinter import *
class Additional(simpledialog.Dialog):
def body(self, master):
#input fields
Label(master, text="Picture 3 Path:").grid(row=1)
#input fields for tags
#add as needed
self.e1 = Entry(master)
self.e1.grid(row=1, column=1, ipadx=150)
return self.e1 # initial focus
def apply(self):
first = self.e1.get()
self.ttag1 = (first)
class Initial(simpledialog.Dialog):
def body(self, master):
#input fields for username and passwords
Label(master, text="Usernames:").grid(row=1),
self.e1 = Entry(master)
self.b1 = Button(master, text = "Add More", bg= 'grey', command= Additional)
self.b1.grid(row=6, column=2, ipadx=75)
self.e1.grid(row=1, column=1, columnspan=2, ipadx=50)
return self.e1 # initial focus
def apply(self):
first = self.e1.get()
self.tag1 = (first)
root = tk.Tk()
root.withdraw()
d = Initial(root)
toor = tk.Tk()
toor.withdraw()
I have tried changing it up but it seems that it's not working right. Any ideas?
When calling the Additional class through the button command, you are not specifying what the parent root should be, and therefore the class fails to initiate. You can solve this by passing the master using a lambda
self.b1 = Button(master, text="Add More", bg='grey', command=lambda: Additional(master))

How to retain the value of an entry field acquired in a popup toplevel window in tkinter?

I cannot get my code to pass the pop up text entry to a global variable i am also attempting to set this global variable as the default text in the entry field in all future instances.
Pop up -> Enter Filepath -> accept&close -> Re-open shows last filepath present as default -> if changed new filepath entry becomes default in future.
import tkinter as tk
from tkinter import ttk
from tkinter import *
master = tk.Tk()
Var1 = StringVar()
Filepath_Var = None
def A_Connect():
root = Tk()
root.title("Entry Field")
def entry_field():
global Filepath_Var
Filepath_Var = Var1.get()
tk.Label(root, text="filepath: ").grid(row=0)
e1 = tk.Entry(root, textvariable=Var1)
tk.Label(root, text="Item Number: ").grid(row=1)
e2 = tk.Entry(root)
#e1.insert(0, r"C:\Users\zxy\ghj\iugf\Bea\something.xlsx")
e1.insert(0, Var1.get())
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
Button(root, text = 'Accept', command = entry_field).grid(row=3, column=1,
sticky=W, pady=4)
root.mainloop()
note = ttk.Notebook(master)
tab1 = tk.Frame(note)
canvas7 = Canvas(tab1, width=520, height=350)
canvas7.pack()
A_Button = tk.Button(tab1, text="A",
width=12, height=3,command=A_Connect, anchor = 'w')
A_Button_Window = canvas7.create_window(20, 120, anchor = 'sw',
window = A_Button)
note.add(tab1, text = " Main ")
note.pack()
master.mainloop()
As a follow up to your earlier question, I encapsulated an example of the (bare bones) desired behavior in two classes:
The main App consists of a button that launches an entry popup; upon filling the fields and accepting, the value in the entry is provided to the App, and the popup closed.
The value entered is stored by the App, and used to populate the entry field of the entry fields in successive popups.
You will probably want to add confirmations and verifications before changing the defaults, and closing the popup, but here, you have the basic skeleton to attach this to.
import tkinter as tk
class PopUpEntry(tk.Toplevel):
def __init__(self, master, default_value=None):
self.master = master
super().__init__(self.master)
if default_value is None:
self.default_entry = 'C:*****\somthing.xlsx'
else:
self.default_entry = default_value
self.title("Entry Field")
tk.Label(self, text="Filepath: ").pack()
self.e1 = tk.Entry(self)
self.e1.insert(0, self.default_entry)
self.e1.pack()
tk.Button(self, text = 'Accept', command=self.entry_field).pack()
def entry_field(self):
self.default_entry = self.e1.get()
self.master.provide_entry_value(self.default_entry)
self.destroy()
class App(tk.Tk):
def __init__(self):
super().__init__()
self.pop_entry = tk.Button(self, text='launch entry', command=self.launch_entry)
self.pop_entry.pack()
self.default_entry_value = None
self.mainloop()
def launch_entry(self):
PopUpEntry(self, self.default_entry_value)
def provide_entry_value(self, value):
self.default_entry_value = value
print(self.default_entry_value)
App()

How Transfer cursor in tkinter?

i wrote bellow code in python 3.6.2 by tkinter,I want the cursor move to password textbox when user press Enter key in username textbox.
from tkinter import *
class Application(Frame):
def __init__(self,master):
super(Application, self).__init__(master)
self.grid()
self.create_main()
def create_main(self):
print("testing")
self.title = Label(self, text=" Stuck In The Circle ")
self.title.grid(row=0, column=2)
self.user_entry_label = Label(self, text="Username: ")
self.user_entry_label.grid(row=1, column=1)
self.user_entry = Entry(self)
self.user_entry.grid(row=1, column=2)
self.pass_entry_label = Label(self, text="Password: ")
self.pass_entry_label.grid(row=2, column=1)
self.pass_entry = Entry(self)
self.pass_entry.grid(row=2, column=2)
self.user_entry = Entry(self, justify="right")
self.pass_entry = Entry(self, justify="right")
self.sign_in_butt = Button(self, text="Sign In",command = self.logging_in)#SIGN IN BUTTON
self.sign_in_butt.grid(row=5, column=2)
def logging_in(self):
user_get = self.user_entry.get()
pass_get = self.pass_entry.get()
root = Tk()
root.title("Stuck in the Circle")
root.geometry("400x100")
app = Application(root)
root.mainloop()
How can do it?
This is actually a lot simpler than I expected it to be.
We can use .bind() to get a callback on the <Return> event. This means that every time the return character is pressed whenever the defined widget is in focus we get a callback.
In order to get it to cycle to the next widget we can use this answer from Bryan Oakley:
def focus_next_window(event):
event.widget.tk_focusNext().focus()
return("break")
text_widget=Text(...) text_widget.bind("<Tab>", focus_next_window)
Important points about this code:
The method tk_focusNext() returns the next widget in the keyboard
traversal hierarchy. the method focus() sets the focus to that widget
returning "break" is critical in that it prevents the class binding
from firing. It is this class binding that inserts the tab character,
which you don't want.
So, applying the same logic in our situation we can use something like the below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry1 = Entry(self.root)
self.entry2 = Entry(self.root)
self.entry1.pack()
self.entry2.pack()
self.entry1.bind("<Return>", self.callback)
def callback(self, event):
event.widget.tk_focusNext().focus()
root = Tk()
App(root)
root.mainloop()

how can i get the input from the entry widget, tkinter, python

I searched how to get the input and this should work but it doesnt...
i dont understand why it doesnt working... its start running and get stuck in the mainloop line... it shows nothing
from Tkinter import *
class GUI:
def __init__(self):
self.root = Tk()
self.label1 = Label(self.root, text="name")
self.label2 = Label(self.root, text="password")
self.entry1 = Entry(self.root)
self.entry2 = Entry(self.root, show="*")
self.button = Button(self.root, text="hello", command=self.printName)
self.button.pack()
self.label1.grid(row=0, sticky=W) # N, S, E, W
self.label2.grid(row=1, sticky=E)
self.entry1.grid(row=0, column=1)
self.entry2.grid(row=1, column=1)
self.c = Checkbutton(self.root, text="forgot my password")
self.c.grid(columnspan=2)
self.root.mainloop()
def printName(self):
print self.entry1.get()
hi = GUI()
The problem is that you are using both grid and pack for widgets that share the same parent. You can't do that -- you have to pick one or the other.
Also, to be pedantic you should ove the call of self.root.mainloop() outside of the __init__. The reason is that with it being inside, the object is never fully created because mainloop won't return until the widget is destroyed. Typically you call mainloop in the same scope that created the root window.
For example:
hi = GUI()
hi.root.mainloop()
If you don't like referencing the internal widget, give GUI a method like start or mainloop:
class GUI():
...
def start(self):
self.root.mainloop()
...
hi = GUI()
hi.start()

Python Tk Label Error with StringVar

I'm going to create a program that resembles the image below. The interface uses one text entry for a name, one button, and two labels. The button should have the text Say hello and when the user clicks the button, the bottom label should display the name with Hi in front of it (see image below)
Here's what I've got
from tkinter import *
from tkinter.ttk import *
def say_hello():
name_var.set(name_entry.get())
def main():
global window, name_var, name_entry
window = Tk()
top_label = Label(window, text='Enter a name below')
top_label.grid(row=0, column=0)
name_var = StringVar()
name_entry = Entry(window, textvariable=name_var)
name_entry.grid(row=1, column=0)
hello_button = Button(window, text='Say hello', command=say_hello)
hello_button.grid(row=2, column=0)
bottom_label = Label(window, text='Hi ' + name_var)
bottom_label.grid(row=3, column=0)
window.mainloop()
main()
When I try to run it I get this error:
Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 5.1\src\debug\tserver_sandbox.py", line 29, in <module> File "C:\Program Files (x86)\Wing IDE 101 5.1\src\debug\tserver_sandbox.py", line 24, in main builtins.TypeError: Can't convert 'StringVar' object to str implicitly
Everything works GUI wise, I'm just not sure how to get the last label that says "Hi Jack" to come up after pressing the button — i.e what my command should be in the hello_button line.
Here's your offensive code:
bottom_label = Label(window, text='Hi ' + name_var)
You can't really add a string and an instance of a class. A Tkinter StringVar isn't actually a string, but like a special thing for the gui to hold a string. That's why it can update automatically and stuff like that. Solution is simple:
bottom_label = Label(window, text = 'Hi ' + name_var.get())
Here's how I did it:
#!/usr/bin/env python2.7
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
self.name_var = tk.StringVar()
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.top_label = tk.Label(self, text='Enter a name below')
self.top_label.grid(row=0, column=0)
self.name_entry = tk.Entry(self)
self.name_entry.grid(row=1, column=0)
self.hello_button = tk.Button(self, text='Say hello', command=self.say_hello)
self.hello_button.grid(row=2, column=0)
self.output = tk.Label(self, textvariable=self.name_var)
self.output.grid(row=3, column=0)
def say_hello(self):
self.name_var.set("Hi {}".format(self.name_entry.get()))
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Ultimately it was very similar to your code. The only thing you were missing was how to use Tkinter.StringVar() correctly. You need to set the bottom label's textvariable to name_var when you create it, and then you should be good to go.
This simple class should do what you want:
from tkinter import Button, Tk, Entry,StringVar,Label
class App():
def __init__(self, **kw):
self.root = Tk()
# hold value for our output Label
self.s = StringVar()
# label above our Entry widget
self.l = Label(self.root, text="Enter name here").pack()
# will take user input
self.e = Entry(self.root)
self.e.pack()
self.b = Button(self.root, text="Say Hello",command=self.on_click).pack()
# textvariable points to our StringVar
self.l2 = Label(self.root, textvariable=self.s).pack()
self.root.mainloop()
# every time the Button is pressed we get here
# an update the StringVar with the text entered in the Entry box
def on_click(self):
self.s.set(self.e.get())
App()
You just need to create a couple of Labels, and Entry widget to take the name and a callback function to update the StringVar value so the label/name value gets updated.

Categories

Resources