Using get() function on tkinter entry widget - python

I am trying to create a standard user ID/PASS login. When I use the next function to check if the entered password and name are right, I always get the "wrong values entered" message. Basically, the variables entry_1 and entry_2 are not storing the input text and I want a solution for that. Maybe any of you guys might propose a solution for that?
I have tried to assign entry_1 and entry_2 to variables but it did'nt work out.
from tkinter import *
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text = "Name")
password = Label(root, text = "Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row = 0, column = 0, sticky = E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row = 0, column =1)
x = "Taha"
password.grid(row = 1, column = 0)
entry_2.grid(row = 1, column =1)
y = "123"
c = Checkbutton(root, text = "Keep in logged in").grid(columnspan = 2 ) # mergers the two columns
def next():
if a == entry_1 and b == entry_2:
print ("Proceed")
else:
print("wrong values entered")
def getname():
return name
Next = Button(root, text = "Next", command=next).grid(row = 3, column = 1)
root.mainloop() # keep runing the code
I want the program to return "Proceed" once correct values are entered.

in your code you're not checking for the user input anywhere. You should use get() to return user input. I've modified your code accordingly. Now if you enter Taha as username and 123 as password, you'll get the "Proceed" message.
from tkinter import *
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text="Name")
password = Label(root, text="Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row=0, column=0, sticky=E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row=0, column=1)
x = "Taha"
password.grid(row=1, column=0)
entry_2.grid(row=1, column=1)
y = "123"
c = Checkbutton(root, text="Keep in logged in").grid(columnspan=2) # mergers the two columns
def next_window():
user_name = entry_1.get()
user_pass = entry_2.get()
if x == user_name and y == user_pass:
print("Proceed")
else:
print("wrong values entered")
def get_name():
return name
Next = Button(root, text="Next", command=next_window).grid(row=3, column=1)
root.mainloop()

thanks to the people who helped, with your help i could find the missing part in the code. i should have used .get() funtion in order to get the entered text back.
here is the upgraded code with some improvements.
from tkinter import *
from tkinter import messagebox
root = Tk() # creates a window and initializes the interpreter
root.geometry("500x300")
name = Label(root, text = "Name")
password = Label(root, text = "Password")
entry_1 = Entry(root)
entry_2 = Entry(root)
name.grid(row = 0, column = 0, sticky = E) # for name to be at right use sticky = E (E means east)
entry_1.grid(row = 0, column =1)
x = "Taha"
password.grid(row = 1, column = 0)
entry_2.grid(row = 1, column =1)
y = "123"
c = Checkbutton(root, text = "Keep in logged in").grid(columnspan = 2 ) # mergers the two columns
def next():
a = entry_1.get()
b = entry_2.get()
if a == "Taha" and b =="123":
messagebox.showinfo("Login", "successfuly logged in ")
root.destroy()
print ("Proceed")
else:
messagebox.showerror("Error", "wrong values entered")
print("wrong values entered")
root.destroy()
Next = Button(root, text = "Next", command=next).grid(row = 3, column = 1)
root.mainloop() # keep runing the code

Related

Tkinter - Wait for several inputs before calculating the results

I am new to tkinter and python in general. I am trying to create a window that allows the user to input information (based on Entry and dropdown menus) and based on their choices, some new input will show up which will then be used to calculate the results. I've tried making a minimum reproducible snippet of code, as the original code is quite long.
The problem is that in the buttons I don't understand which command to include so that the program waits for all input before executing the rest of the code. Now it seems that no matter what I include it goes directly to the result part of the code.
I've tried having a function that saves the input and calculates the result as the command for the button, but it still does not wait.
The wait_variable as far as I understood only works for one variable?
import tkinter as tk
root = tk.Tk()
root.geometry("1500x800")
Intro_Label = tk.Label(root, text = "Welcome")
Intro_Label.grid(row=0, column=0)
entry_1 = tk.Entry()
entry_1.insert(0, 2.5) #default value
Label_1 = tk.Label(root, text="Input 1")
Label_1.grid(row=2, column=0)
entry_1.grid(row=2, column=1)
Label_2 = tk.Label(root, text="Input 2 ")
#Options for dropdown menu for transport method
I2_clicked = tk.StringVar()
I2_clicked.set("Choose from dropdown menu")
input2_opt = ["a", "b"]
input2 = tk.OptionMenu( root , I2_clicked , *input2_opt )
Label_3 = tk.Label(root, text="Input 2 ")
#Options for dropdown menu for transport method
I3_clicked = tk.StringVar()
I3_clicked.set("Choose from dropdown menu")
input3_opt = ["x", "y"]
input3 = tk.OptionMenu( root , I3_clicked , *input3_opt )
Label_2.grid(row=3, column=0)
input2.grid(row=3, column=1)
Label_3.grid(row=3, column =3)
input3.grid(row=3, column = 4)
def input_calculations():
first_input = entry_1.get()
if I2_clicked.get() == "a":
if I3_clicked.get() == "x":
entry_4 = tk.Entry()
Label_4 = tk.Label(root, text="Input for x|a")
entry_4.insert(0, 5) #dummy default value
entry_4.grid(row = 4, column = 1 )
Label_4.grid(row = 4, column = 0)
entry_5 = tk.Entry()
Label_5 = tk.Label(root, text="Second input for x|a")
entry_5.insert(0, 4) #dummy default value
entry_5.grid(row = 4, column = 4)
Label_5.grid(row = 4, column = 3)
#wait for both inputs before executing the calculations
save_button = tk.Button(root, text ="Calculate results", command= )
save_button.grid(row = 5, column = 6)
#calculate some results
result = float(entry_4.get())* float(entry_5.get())
elif I3_clicked.get() == "y":
entry_6 = tk.Entry()
Label_6 = tk.Label(root, text="Input for y|a")
entry_6.insert(0, 6) #dummy default value
entry_6.grid(row = 4, column = 1 )
Label_6.grid(row = 4, column = 0)
entry_7 = tk.Entry()
Label_7 = tk.Label(root, text="Second input for y|a")
entry_7.insert(0, 7) #dummy default value
entry_7.grid(row = 4, column = 4)
Label_7.grid(row = 4, column = 3)
entry_8 = tk.Entry()
Label_8 = tk.Label(root, text="Third input for y|a")
entry_8.insert(0, 8) #dummy default value
entry_8.grid(row = 4, column = 6)
Label_8.grid(row = 4, column = 5)
save_button = tk.Button(root, text ="Calculate results", command= )
save_button.grid(row = 5, column = 6)
#wait for input before executing the next lines - what to insert here ??
result = float(entry_6.get()) / float(entry_7.get()) * float(entry_8.get())
#continues for all combinations (b and y, b and x) - different inputs, different calculations for each combo
return result
btn = tk.Button(root, text="Confirm", width=15,command=input_calculations)
btn.grid(row= 10, column= 5)
root.mainloop()
You could link the buttons to functions that do the calculations.
Example function:
def button_pressed():
result = float(entry_6.get()) / float(entry_7.get()) * float(entry_8.get())
You could either pass the entries as arguments in a lambda, or make the whole program inside of a class. This way every method can access all of the widgets.
For your save button you would then need to add the function to the command parameter:
save_button = tk.Button(root, text ="Calculate results", command=button_pressed)
You could make multiple functions / methods if you use a class to do the steps you need.

Python: GUI based "reverse entry" using recursion failing

I am trying to make a Python program that asks the user for a number then reverses it using recursion. My attempt is below, but my code gives me TypeError: unsupported operand type(s) for //: 'Entry' and 'int' - any ideas?
from tkinter import *
def reverseInteger(n, r):
if n==0:
return r
else:
return reverseInteger(n//10, r*10 + n%10)
window = Tk()
window.title("Reverse Integer")
frame1 = Frame(window)
frame1.pack()
number = StringVar()
numEntry = Entry(frame1, textvariable=number)
btGetName = Button(frame1, text = "Calculate", command = reverseInteger(numEntry, 0))
label3 = Label(frame1)
numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")
window.mainloop()
Your recursive function is perfectly fine but there are several other
problems in your code.
The main one is that the command parameter of Button must be the
function that will be called when the user presses on the buttton. In
your code, command is set to the return value of reverseInteger
which is an int. So there is a problem here.
Also it seems to me that you want to put the result of your
calculation in label3 so your StringVar should be attached to it
and not to numEntry.
So here is a version that seems ok to me:
from tkinter import *
def reverseInteger(n, r):
if n==0:
return r
else:
return reverseInteger(n//10, r*10 + n%10)
def reverse(): # called when the user click on the button
value = reverseInteger(int(numEntry.get()), 0)
number.set(value) # change the text of the label
window = Tk()
window.title("Reverse Integer")
frame1 = Frame(window)
frame1.pack()
number = StringVar()
numEntry = Entry(frame1)
btGetName = Button(frame1, text = "Calculate", command = reverse)
label3 = Label(frame1, textvariable=number)
numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")
window.mainloop()

How to view and unview a password in tkinter

I have a program (below) that creates an entry box that shows only '*' when you type in it and it creates a button next to the text box. I want the button to show what has been typed in the entry box while it is being pressed. I have tried to use <Button-1> and <ButtonRelease-1> but to no avail.
import tkinter as tk
def myFunc() :
#Something#
pass
root = tk.Tk()
root.title('Password')
password = tk.Entry(root, show = '*')
password.grid(row = 0, column = 1)
password_label = tk.Label(text = 'Password:')
password_label.grid(row = 0, column = 0)
button = tk.Button(text = '.', command = myFunc)
button.grid(row = 0, column = 2)
Try this:
import tkinter as tk
def show_stars(event):
password.config(show="*")
def show_chars(event):
password.config(show="")
root = tk.Tk()
root.title("Password")
password = tk.Entry(root, show="*")
password.grid(row=0, column=1)
password_label = tk.Label(text="Password:")
password_label.grid(row = 0, column=0)
button = tk.Button(text="Show password")
button.grid(row=0, column=2)
button.bind("<ButtonPress-1>", show_chars)
button.bind("<ButtonRelease-1>", show_stars)
Using the bindings that #BryanOakley suggested
Only if button is pressed it changes the text from * to the text entered.
import tkinter as tk
def myFunc():
#Something#
if password.cget("show")=="*":
password.configure(show="")
elif password.cget("show") =="":
password.configure(show="*")
root = tk.Tk()
root.title('Password')
password = tk.Entry(root, show = '*')
p = password
password.grid(row = 0, column = 1)
password_label = tk.Label(text = 'Password:')
password_label.grid(row = 0, column = 0)
button = tk.Button(text = '.', command = myFunc)
button.grid(row = 0, column = 2)
root.mainloop()

How to create a number of Labels and Entry widgets, and get data from them in Tkinter with loop

I need to create a couple of Labels and Entry fields using Tkinker, they all will be the same, only difference is a text in the label which i could have in a list.
This is what the problem looks like while done in a simple way, i want to do it smarter, using some kind of loop, so i could expand it.
from tkinter import *
root = Tk()
question1 = Label(root, text="Please give data number one")
question1.grid(row=1, column=0)
field1 = Entry(root)
field1.grid(row=1, column=1)
question2 = Label(root, text="Please give data number two")
question2.grid(row=2, column=0)
field2 = Entry(root)
field2.grid(row=2, column=1)
question3 = Label(root, text="Please give data number three")
question3.grid(row=3, column=0)
field3 = Entry(root)
field3.grid(row=3, column=1)
question4 = Label(root, text="Please give data number four")
question4.grid(row=4, column=0)
field4 = Entry(root)
field4.grid(row=4, column=1)
data1 = field1.get()
data2 = field2.get()
data3 = field3.get()
data4 = field4.get()
root.mainloop()
I thought abour something like this but i don't know how to get values from Enter widgets.
from tkinter import *
root = Tk()
questions = ["Please give data number one",
"Please give data number two"
"Please give data number three"
"Please give data number four"
]
for question in enumerate(questions):
ask = Label(root, text=question[1])
ask.grid(row=(question[0] + 1), column=0)
field = Entry(root)
field.grid(row=(question[0] + 1), column=1)
root.mainloop()
You need to do two things:
Firstly keep a reference to the widget, and then use the get() method to get the string.
For an example:
self.entry = Entry(...)
...some code
print("the text is", self.entry.get())
Sample Get Entries:
class InputPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self,parent)
label = Label(self, text="Please give data number four")
label.grid(row=0, column=0, sticky ='n', columnspan =2)
# i brought your variable in the class for example sake
namesInput = ["First:", "second:", "Third:", "Fourth:", "Fifth:"]
self.entryWidgets = [] # we want to call this in another function so we assign it as self.variableName
labelWidgets = []
#LOOP TO CREATE WIDGETS
for i in range(0, len(namesInput)):
labelWidgets.append(Label(self, text = namesInput[i]))
self.entryWidgets.append(Entry(self))
labelWidgets[-1].grid(row= i+1, column =0, sticky='e')
self.entryWidgets[-1].grid(row= i+1, column = 1, sticky='w')
submit = Button(self, text = "Submit", command = self.getEntries)
submit.grid(row = 6, column =0, columnspan =2)
def getEntries(self):
results = []
for x in self.entryWidgets: # i.e for each widget in entryWidget list
results.append(x.get())
print(results)

Data from subit button to e-mail msg

I stuck on this one and i dont know how to get #Button1, 2 and 3 under Submit button in def callback:
also how get all collected data from Submit button in def callback: and paste into Msg.HTMLBody
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import win32com.client
root = tk.Tk()
v = tk.IntVar()
# Name & Input
tk.Label(root, text="Full Name").grid(row=0, column = 0)
e1 = tk.Entry(root)
e1.grid(row=0, column = 1)
# Employer Number & Input
tk.Label(root, text="Employy Number").grid(row=1, column = 0)
e2 = tk.Entry(root)
e2.grid(row=1, column = 1)
# Question 1
tk.Label(root,text="Are you happy in your job?", justify = tk.LEFT, padx = 20).grid(row=4, column = 0)
#Button 1
tk.Radiobutton(root,text="Not happy",fg="red",padx = 200,variable=v, value=1).grid(row=5, column = 0)
#Button 2
tk.Radiobutton(root, text="Happy",fg="blue",padx = 20,variable=v,value=2).grid(row=5, column = 1)
#Button 3
tk.Radiobutton(root, text="Very Happy",fg="green",padx = 20,variable=v,value=3).grid(row=5, column = 2)
# Tick box
tk.Label(root,text="IF you requide for extra training please tick the box.", justify = tk.LEFT, padx = 20).grid(row=6, column = 0)
var1 = IntVar()
Checkbutton(root, text="APR", variable=var1).grid(row=7, column = 0)
var2 = IntVar()
Checkbutton(root, text="THS", variable=var2).grid(row=8, column = 0)
var3 = IntVar()
Checkbutton(root, text="GOODS IN", variable=var3).grid(row=9, column = 0)
var4 = IntVar()
Checkbutton(root, text="DESPATCH", variable=var4).grid(row=10, column = 0)
var5 = IntVar()
Checkbutton(root, text="LLOP", variable=var5).grid(row=11, column = 0)
var6 = IntVar()
Checkbutton(root, text="REACH TRUCK", variable=var6).grid(row=12, column = 0)
var7 = IntVar()
Checkbutton(root, text="CBT", variable=var7).grid(row=13, column = 0)
# Add comment
tk.Label(root, text="If you have any additional comments about your current position, manager ar any thing else please share with us.").grid(row=14, column= 0)
e3 = tk.Entry(root)
e3.grid(row=15, column=0)
#Submit button
def callback():
print("Full name:",e1.get())
print("Employy Number:",e2.get())
print("APR",var1.get())
print("THS", var2.get())
print("GOODS IN ", var3.get())
print("DESPATCH ", var4.get())
print("LLOP ", var5.get())
print("REACH TRUCK ", var6.get())
print("CBT ", var7.get())
print("Addition comment:",e3.get())
#Sending an e-mail
people = ['my e-mail']
for i in people:
o = win32com.client.Dispatch("Outlook.Application")
Msg = o.CreateItem(0)
Msg.Importance = 0
Msg.Subject = 'Subject'
Msg.HTMLBody = ("")
Msg.To = i
Msg.SentOnBehalfOfName = "sender"
Msg.ReadReceiptRequested = True
Msg.Send()
MyButton1 = Button(root, text="Submit", width=10, command=callback)
MyButton1.grid(row=16, column=0)
#Sending an e-mail
people = ['my e-mail']
for i in people:
o = win32com.client.Dispatch("Outlook.Application")
Msg = o.CreateItem(0)
Msg.Importance = 0
Msg.Subject = 'Subject'
Msg.HTMLBody = ("")
Msg.To = i
Msg.SentOnBehalfOfName = "sender"
Msg.ReadReceiptRequested = True
Msg.Send()
root.mainloop()

Categories