from tkinter import *
app = Tk()
app.title("First Software")
app.minsize(500, 500)
#For Input Declaration
UserName = StringVar()
pass1 = IntVar()
class Functions:
def username(self, UserName):
self.UserName = Username
print(UserName.get())
def password(self, pass1):
self.pass1 = pass1
print(pass1.get())
#---Label---
label = Label(text='Enter any Number between 1 and 100...').pack()
#---Entry---
entry = Entry(app, textvariable=UserName).pack()
entry1 = Entry(app, textvariable=pass1).pack()
#---Buttton---
button = Button(text='Submit', command=Functions).pack()
app.mainloop()
After running this code, How can I get separate input of Username and password by using this method. I'm lil bit confused right now!
command=Functions tells Tkinter to create an instance of your Functions class when the Submit button is pressed. But it doesn't tell it to call the functions defined inside Functions. However, that class definition is a bit odd, and you don't really need a class to contain those functions. Instead, we can write a simple function that gets the values of UserName and pass1 and prints them.
I've made a few other minor changes to your code.
import tkinter as tk
app = tk.Tk()
app.title("First Software")
#app.minsize(500, 500)
#For Input Declaration
UserName = tk.StringVar()
pass1 = tk.IntVar()
def print_entries():
print('User name:', UserName.get())
print('Password:', pass1.get())
tk.Label(app, text='User name.').pack()
entry = tk.Entry(app, textvariable=UserName)
entry.pack()
tk.Label(app, text='Password\nEnter any Number between 1 and 100').pack()
entry1 = tk.Entry(app, textvariable=pass1)
entry1.pack()
tk.Button(app, text='Submit', command=print_entries).pack()
app.mainloop()
This code doesn't actually need the names entry and entry1, but I kept them in case you want to add code that does need to refer to those widgets by name.
Note that you should not do
entry = Entry(app, textvariable=UserName).pack()
The .pack method returns None, so the above statement assigns the value of None to entry. Instead, we do
entry = tk.Entry(app, textvariable=UserName)
entry.pack()
That assigns the new Entry widget to the name entry and then calls its .pack method to pack it into the window.
If you like, you can wrap that code up in a class, but I wouldn't bother with a simple GUI like this. But this is one way to do it:
import tkinter as tk
class App:
def __init__(self):
root = tk.Tk()
root.title("First Software")
#root.minsize(500, 500)
#For Input Declaration
self.UserName = tk.StringVar()
self.pass1 = tk.IntVar()
tk.Label(root, text='User name.').pack()
entry = tk.Entry(root, textvariable=self.UserName)
entry.pack()
tk.Label(root, text='Password\nEnter any Number between 1 and 100').pack()
entry1 = tk.Entry(root, textvariable=self.pass1)
entry1.pack()
tk.Button(root, text='Submit', command=self.print_entries).pack()
root.mainloop()
def print_entries(self):
print('User name:', self.UserName.get())
print('Password:', self.pass1.get())
App()
Related
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.
So far I have tried the advice from u/OA998
"""https://www.reddit.com/r/learnpython/comments/45h05k/solved_kernel_crashing_when_closing_gui_spyder/
My code is supposed to just open up a window with two labels and an entry field. The code works fine if I restart the Kernel but just running it after closing the window will result in an window popping up that has no text (from the StringVar). The third time it doesn't even open anymore. I'm not quite sure what causes this."""
Code:
""" create a GUI inside a class (this allows variables to be added and changed by several parts in the GUI). By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
from tkinter import *
""" create a GUI inside a class (this allows variables to be added and changed by several parts in the GUI)"""
""" By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments."""
class TESTGUI:
def __init__(self, window):
"""We will use an entry widget, and StringVar to keep track of the current text in the
box, and a label to display a message."""
"""labelpositioning"""
margin = 2
self.spacer = Label(window, width=margin, height=margin)
self.spacer.grid(column=0,row=0)
"""for toogle button create StringVar in tkinter class to hold the text"""
"""labeltexts"""
self.labelText_1 = StringVar()
self.labelText_1.set("begin experiment")
self.labelText_2 = StringVar()
self.labelText_2.set("calibrate")
"""labelformat"""
self.label = Label(window, textvariable=self.labelText_1, width=12, height=3, borderwidth=3, relief=SOLID)
self.label.grid(column=1, row=1)
self.label = Label(window, textvariable=self.labelText_2, width=12, height=3, borderwidth=3, relief=SOLID)
self.label.grid(column=2, row=1)
"""labelbutton"""
self.button = Button(window, text="press", command=self.pressed_button_1)
self.button.grid(column=1,row=2)
self.button = Button(window, text="press", command=self.pressed_button_2)
self.button.grid(column=2,row=2)
"""Entry(password)Label"""
self.entryLabel_1 = Label(window, text = "enter your password")
self.entryLabel_1.grid(column=0,row=3)
""" Next add a StringVar to hold the password and Entry box to type the password."""
""" The trace function will call a checkStrength() function when the StringVar is changed."""
self.password = StringVar()
self.password.trace("w", lambda name, index, mode, password=self.password:self.checkStrenght())
self.entry = Entry(window, textvariable=self.password)
self.entry.grid(column=1, row=3)
""" then create the StringVar to hold the strength string, and the label to display it. """
self.strenghtText = StringVar()
self.strenghtText.set("")
self.strenghtLabel = Label(window, textvariable=self.strenghtText, width=10)
self.strenghtLabel.grid(column=3, row=3)
"""CheckStrenghtFunctionOfEntry"""
def checkStrenght(self):
lenght = len(self.password.get())
if lenght == 0:
self.strenghtText.set("")
self.strenghtLabel.config(bg="SystemWindowBody")
elif lenght >= 1:
self.strenghtText.set("strong")
self.strenghtText.config(bg = "green3")
"""ButtonFunction"""
def pressed_button_1(self):
if self.labelText_1.get() == "begin experiment":
self.labelText_1.set("abort experiment")
else:
self.labelText_1.set("begin experiment")
def pressed_button_2(self):
if self.labelText_2.get() == "calibrate":
self.labelText_2.set("recalibrate")
else:
self.labelText_2.set("calibrate")
""" define Variables for window size """
width=300
height=300
""" define tk for used variable to use tkinter class """
if __name__ == "__main__":
window = Tk()
window.minsize(width, height)
window.title("Photonics Lab")
gui = TESTGUI(window)
window.mainloop()
I'm trying to make an example for some high school students using tkinter with multiple forms, and accessing form data in different functions. I'm trying to keep the example simple, but having a small problem. The sv3 & sv4 variables are not getting the values from the second form. Any suggestions or ideas?
from tkinter import *
root = Tk()
sv1 = StringVar()
sv2 = StringVar()
sv3 = StringVar()
sv4 = StringVar()
#first function - this DOES NOT take text from entry widgets and displays, but should
def callback2():
test2 = sv3.get()
print(test2)
print (sv4.get())
print("show second form entry widgets values")
return True
#first function - this takes text from entry widgets and displays
def callback():
test = sv1.get()
print(test)
print (sv2.get())
print("show first form entry widgets values")
new_form()
return True
#new form
def new_form():
newfrm = Tk()
entry3 = Entry(newfrm, textvariable=sv3).pack()
entry4 = Entry(newfrm, textvariable=sv4).pack()
button = Button(newfrm, text="Click Me", command=callback2).pack()
newfrm.mainloop()
#initial form
def main_form():
entry1 = Entry(root, textvariable=sv1).pack()
entry2 = Entry(root, textvariable=sv2).pack()
button = Button(root, text="Click Me", command=callback).pack()
root.mainloop()
main_form()
Here how to avoid using multiple Tk instances and manually transfers the values from the first two Entrys to the second pair. See lines with #### comments.
from tkinter import *
root = Tk()
sv1 = StringVar()
sv2 = StringVar()
sv3 = StringVar()
sv4 = StringVar()
#first function - this now take text from entry widgets and displays as it should.
def callback2():
test2 = sv3.get()
print(test2)
print (sv4.get())
print("show second form entry widgets values")
return True
#first function - this takes text from entry widgets and displays
def callback():
test = sv1.get()
print(test)
print (sv2.get())
print("show first form entry widgets values")
new_form()
return True
#new form
def new_form():
#### newfrm = Tk()
newfrm = Toplevel() #### Instead.
sv3.set(sv1.get()) #### Trasfer value.
sv4.set(sv2.get()) #### Trasfer value.
entry3 = Entry(newfrm, textvariable=sv3).pack()
entry4 = Entry(newfrm, textvariable=sv4).pack()
button = Button(newfrm, text="Click Me", command=callback2).pack()
newfrm.mainloop()
#initial form
def main_form():
entry1 = Entry(root, textvariable=sv1).pack()
entry2 = Entry(root, textvariable=sv2).pack()
button = Button(root, text="Click Me", command=callback).pack()
root.mainloop()
main_form()
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()
from Tkinter import *
root = Tk()
root.geometry("230x100")
L1 = Label(root, text="Login page", bg = "blue", fg = "white")
L1.pack(fill = X, ipadx = 5, ipady = 5)
V = StringVar(root, value='Enter username here')
E1 = Entry(root, textvariable=V)
E1.pack(side = LEFT, padx = 5, pady = 5)
def Login():
username = V.get()
print "Username is '" + username + "'"
B1 = Button(root, text ="Login" , command = Login)
B1.pack(side = RIGHT, fill = X, pady=5)
mainloop()
I have been trying to get the value of 'username' in the function Login() to use it on another python program.
I have tried setting it as global variable and changing its scope but I am not getting anything.
I need to use the value of 'Username' outside the function Login(). Please provide your insights.
Think about scope for a moment. When your program ends, all memory (meaning variables, objects, etc.) are released. The only 2 ways I can think of to pass something from one program to another is:
1) Write the username value to a file which the next program can read as part of its startup.
2) Have a third "controller" or "launcher" program that runs the program above, takes a return value from that program, then passes that value as a parameter to the next program.
But in any case, you will have to save that value past the scope of the program above.
1) Create a python file say 'global_vars.py' and add this line in it.
#global_vars.py
global_V = ''
2) Import this global_vars.py wherever you want set the variable as below:
#main.py
from Tkinter import *
import global_vars
root = Tk()
root.geometry("230x100")
L1 = Label(root, text="Login page", bg = "blue", fg = "white")
L1.pack(fill = X, ipadx = 5, ipady = 5)
V = StringVar(root, value='Enter username here')
#Set the global variable
global_vars.global_V = V
E1 = Entry(root, textvariable=V)
E1.pack(side = LEFT, padx = 5, pady = 5)
3) Consider you want to use this value in python program present in file "test.py". Just import global_vars.py and use this variable
#test.py
import global_vars.py
def printUserName():
print "Username is -", global_vars.global_V
If you have to python files, one called main.py that contains your main program (I assumed it was a GUI program) and the login.py file that contains the login program.
main.py
from tkinter import Tk, Label
from login import LoginGUI
class mainGUI(Tk):
def __init__(self):
Tk.__init__(self)
Label(self, text="You need to login first",
bg="blue", fg="white").pack(fill="x", ipadx=5, ipady=5)
# open login dialog
login = LoginGUI(self)
# wait for the user to log in
self.wait_window(login)
username = login.getLogin()
Label(self,
text="Your username is " + username).pack(fill="x", ipadx=5, ipady=5)
self.mainloop()
if __name__ == '__main__':
mainGUI()
login.py
from tkinter import Toplevel, StringVar, Entry, Button, Label
from tkinter import Toplevel, StringVar, Entry, Button, Label
class LoginGUI(Toplevel):
def __init__(self, master):
Toplevel.__init__(self, master)
self.transient(master)
self.geometry("230x100")
Label(self, text="Login page",
bg="blue", fg="white").pack(fill="x", ipadx=5, ipady=5)
self.username = ""
self.usernameVar = StringVar(self, value='Enter username here')
E1 = Entry(self,
textvariable=self.usernameVar)
E1.pack(side="left", padx=5, pady=5)
Button(self, text="Login",
command=self.Login).pack(side="right", fill="x", pady=5)
E1.focus_set()
def Login(self):
self.username = self.usernameVar.get()
self.destroy()
def getLogin(self):
return self.username
If your main program have no GUI, replace Toplevel by Tk in login.py and add a self.mainloop at the end of the __init__ method.
You can launch the other program using subprocess, or refactor the other program so the username can be passed as the parameter of a function, and import that program as module of your main program.