Tkinter - show dialog with options and change password buttons - python

I use a python program called Thonny. Its used to make another box that said 'You have made it into the main application' inside but I removed that piece of text for now. I would like it to show a options button and a change password button. This is the code:
import tkinter as tk
class Mainframe(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = FirstFrame(self)
self.frame.pack()
def change(self, frame):
self.frame.pack_forget() # delete currrent
frame = frame(self)
self.frame.pack() # make new frame
class FirstFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
lbl = tk.Label(self, text='Enter password')
lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
btn = tk.Button(self, text="Done", command=self.check)
btn.pack()
btn = tk.Button(self, text="Cancel", command=self.quit)
btn.pack()
def check(self, event=None):
if self.pwd.get() == 'password':
self.master.change(SecondFrame)
else:
self.status.config(text="Wrong password")
class SecondFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Main application")
master.geometry("600x400")
def options_button(self):
def set_password(self):
e = tk.Entry(master, show="*", textvariable=self.password_set2)
e.pack()
but1 = tk.Button(self, text="Done", command=self.password_set)
but1.pack()
b = tk.Button(self, text="Set your password", command=self.set_password)
b.pack()
c = tk.Button(self, text="Options", command=self.options_button)
c.pack()
if __name__=="__main__":
app=Mainframe()
app.mainloop()
This is What is not working.
This is what it originally did

So I had a little bit of a play around and I think this is what your after. I also changed your code a little bit as I always feel its best to put self infront of all widgets on multiclass applications.
import tkinter as tk
class FirstFrame(tk.Frame):
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack()
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
self.lbl = tk.Label(self, text='Enter password')
self.lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
self.btn = tk.Button(self, text="Done", command=self.check)
self.btn.pack()
self.btn = tk.Button(self, text="Cancel", command=self.quit)
self.btn.pack()
def check(self, event=None):
if self.pwd.get() == app.password:
self.destroy() #destroy current window and open next
self.app= SecondFrame(self.master)
else:
self.status.config(text="Wrong password")
class SecondFrame(tk.Frame):
#re organised a lot in here
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack()
master.title("Main application")
master.geometry("600x400")
self.c = tk.Button(self, text="Options", command=self.options_button)
self.c.pack()
self.e = tk.Entry(self.master, show="*")
def options_button(self):
self.e.pack()
self.but1 = tk.Button(self, text="Change password", command=self.set_password)
self.but1.pack()
def set_password(self):
app.password=self.e.get()
if __name__=="__main__":
root = tk.Tk() #removed your mainframe class
app=FirstFrame(root)
#set an attribute of the application for the password
#similar to a global variable
app.password = "password"
root.mainloop()
So with what I have done you get prompted for the password and if you get it right it goes to the next scree, then an options button appears and if it is clicked then an entry box appears allowing the user to change the password

Related

Cannot call show_frame function in tkinter outise of its class

With the code below (that I took from sentdex) I am trying to raise PageOne window when the correct password("123") is inserted in the first page. However, I get the error: TypeError: show_frame() missing 1 required positional argument: 'cont'. Isn't PageOne the argument ? Why is not working ? Could you also please explain what "controller" variable does ?
Thank you very much in advance.
import tkinter as tk
import tkinter as tk
from PIL import Image,ImageTk
LARGE_FONT= ("Verdana", 12)
class Root(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.entry=tk.Entry(self, width = 35)
self.entry.insert(0, 'Enter password')
self.entry.config(fg = "grey")
# entry.bind('<FocusIn>', self.EntryFieldClicked)
# entry.bind("<Return>", (lambda event: self.SubmitPass()))
self.entry.place(relx=.5, rely=.3,anchor = tk.CENTER)
button=tk.Button( self,text="Show Password", width = 20,command = self.ShowPass).place(relx=.5, rely=.4,anchor = tk.CENTER)
button=tk.Button(self,text="Submit",width = 20, command=self.SubmitPass).place(relx=.5, rely=.5,anchor = tk.CENTER)
self.entry.config(fg = "grey")
self.entry.bind('<FocusIn>', self.EntryFieldClicked)
self.entry.bind("<Return>", (lambda event: self.SubmitPass ))
label=tk.Label(self,text="Log in to continue")
label.pack()
button = tk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
def EntryFieldClicked(self,event):
if self.entry.get() == 'Enter password':
self.entry.delete(0, tk.END)
self.entry.insert(0, '')
self.entry.config(fg = 'black', show = "*")
def ShowPass(self):
self.entry.config(fg = 'black', show = "")
def SubmitPass(self):
global Password
Password = self.entry.get()
if Password == "123":
Root.show_frame(PageOne)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
self.controller = controller
button1 = tk.Button(self, text="Back to Home",
command=lambda: self.controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.pack()
app = Root()
app.mainloop()
Blockquote
The problem is this line:
Root.show_frame(PageOne)
You are calling the method on the class rather than the instance, so the first argument is passes to the self parameter.
Your class needs to keep a reference to the controller, so that you can call the method via the controller.
class StartPage(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
def SubmitPass(self):
global Password
Password = self.entry.get()
if Password == "123":
self.controller.show_frame(PageOne)

CLASS MATH -- Need Help getting an Int Value from XY -- Super Lost

Okay, so I am been learning python for 2 weeks and implementing TkInter now, I am trying to make an project where the user can set an Alarm and when the alarm rings the user will hit stop then the program will ask the user some random math questions, I been messing around and got everything up to the Math problem to work, I have a lot of placeholders in place and I am stuck with getting the answer of x and y to return to an INT, I have it made where it will show what x+y will equal and what the user enter but when I run the while loop my program just freezes. I assume its because the answer returns as a Label and that's not an INT, so all my issues are in my Math Class and have been trying for 3 days and cant figure it out. Please anything will be helpful, I tried using the .get method but that also gives me errors.
import tkinter as tk
import time
import datetime
from tkinter import *
from winsound import PlaySound, SND_FILENAME, SND_LOOP, SND_ASYNC
import random
class WakeUpApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side='top', fill='both', expand='true',)
container.grid_rowconfigure(0, minsize=400, weight=1)
container.grid_columnconfigure(0, minsize=250, weight=2)
self.frames = {}
for F in (Alarm, Chooser, Difficulty, Math):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_frame(Alarm)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
present = datetime.datetime.now()
now = present.strftime("%H:%M:%S")
class Alarm(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
Alarm.hour = tk.StringVar()
Alarm.min = tk.StringVar()
Alarm.sec = tk.StringVar()
hour_a = tk.Entry(self, text=Alarm.hour, width=4).place(x=50, y=50)
min_a = tk.Entry(self, text=Alarm.min, width=4).place(x=70, y=50)
sec_a = tk.Entry(self, text=Alarm.sec, width=4).place(x=90, y=50)
current_time = tk.Label(self, text=f'Current Time: {now}').place(x=0, y=30)
set_time = tk.Label(self, text='Set Time').place(x=0, y=50)
'''
VERY IMPORTANT -- THIS CODE STARTS THE ALARM
setalarm = tk.Button(self, text='Set Alarm', command=lambda: wake())
setalarm.place(x=90, y=90)
'''
setalarm = tk.Button(self, text='Set Alarm', command=lambda: controller.show_frame(Chooser))
setalarm.place(x=90, y=90)
def wake():
alarm_time = f'{Alarm.hour.get()}:{Alarm.min.get()}:{Alarm.sec.get()}'
alarm_clock(alarm_time)
def play_sound(self,):
PlaySound('Sound.wav', SND_FILENAME|SND_LOOP|SND_ASYNC)
def stop_sound(self):
PlaySound(None, SND_FILENAME)
def alarm_clock(alarm_time):
while True:
time.sleep(1)
present = datetime.datetime.now()
now = present.strftime("%H:%M:%S")
print(now)
if now == alarm_time:
break
if now == alarm_time:
play_sound(self)
testbutton = Button(self, text='pls work', command=lambda: stop_sound(self))
testbutton.pack()
class Chooser(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text='Please Choose Your Wake Up Game')
label.pack(pady=50, padx=50)
math = tk.Button(self, text='Math Game',
height=5, width=15,
command=lambda: controller.show_frame(Difficulty))
math.place(x=125, y=75)
guesser = tk.Button(self, text='Guessing Game',
height=5, width=15,
command=lambda: controller.show_frame(Alarm))
guesser.place(x=125, y=175)
class Difficulty(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text='Please Choose Your Difficulty for the Questions')
label.pack(pady=50, padx=50)
level1 = tk.Button(self, text='Level 1 \n ie: 12+17',
height=5, width=15,
command=lambda: controller.show_frame(Math))
level1.place(x=125, y=75)
level2 = tk.Button(self, text='Level 2 \n ie: 12*9',
height=5, width=15,
command=lambda: controller.show_frame(Alarm))
level2.place(x=125, y=175)
level3 = tk.Button(self, text='Level 3 \n ie: 6*7+21',
height=5, width=15,
command=lambda: controller.show_frame(Alarm))
level3.place(x=125, y=275)
class Math(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar()
ab = tk.IntVar()
x = random.randint(1, 10)
y = random.randint(1, 10)
xy = int(x + y)
problem = tk.Label(self, text=f'{x} + {y}').place(x=0, y=30)
goal = tk.Label(self, text=xy).place(x=0, y=90)
solution = tk.Entry(self, text=z).place(x=0, y=50)
new = tk.Entry(self, text=ab).place(x=0, y=70)
def answer2(self):
py_guess = tk.Label(self, text=ab.get()).place(x=125, y=120)
button2 = tk.Button(self, text='GIVE ME Z PLS', command=lambda: answer())
button2.pack()
button2 = tk.Button(self, text='The Problem', command=lambda: answer2(self))
button2.pack()
def answer():
user_guess = tk.Label(self, text=z.get()).place(x=125, y=100)
level1(user_guess)
def level1(user_guess):
keepGoing = True
while keepGoing:
if (z == xy):
good = tk.Label(self, text='good job').pack()
keepGoing = False
else:
bad = tk.Label(self, text='nope go again').pack()
string_solution = solution.get()
int_solution = int(string_solution)
app = WakeUpApp()
app.mainloop()

Using a variable from one class to another tkinter

Here is the full code for test please run it and tell me if I can store username and password outside the class after destroy the frame
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.title('Instagram Bot')
self.geometry("500x500")
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
self.password = self.password.get()
self.username = self.username.get()
# if(username.get('text') == None or password.get('text') == None):
# tk.Button(self, text="Login",
# command=lambda: master.switch_frame(StartPage)).pack()
# else:
tk.Button(self, text="Login", command=lambda: master.switch_frame(PageOne) and login_data()).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
print(StartPage.username, StartPage.password)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/init.py", line 1705, in call
return self.func(*args) File "scofrlw.py", line 71, in start_hashtag
print(StartPage.username, StartPage.password) AttributeError: type object 'StartPage' has no attribute 'username'
In the code below, i have been storing the credentials inside the master (SampleApp) which is accessible from your class PageOne aswell.
Alternatively, you may consider storing the credentials in a dict, and passing it
to your PageOne during initialization.
import tkinter as tk
from tkinter import *
#from PIL import Image, ImageTk
from tkinter import filedialog
class SampleApp(tk.Tk):
def __init__(self):
self.test = "I am the MasterAPP"
tk.Tk.__init__(self)
self._frame = None
self.title('Instagram Bot')
self.geometry("500x500")
self.switch_frame(StartPage)
self.username = None
self.password = None
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
tk.Button(self, text="Login",
command=lambda:
self.login()
).pack()
def login(self):
self.save_credentials()
self.master.switch_frame(PageOne)
def save_credentials(self):
self.master.password = self.password.get()
self.master.username = self.username.get()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
print(self.master.username, self.master.password)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
I would make a dictionary of the username and password, but depending on your GUI, I don't know the best option for you
Make the dictionary
dictionary = {}
class StartPage(tk.Frame):
...
Add values for the username and password.
def login_credentials(self):
dictionary['password'] = self.password.get()
dictionary['username'] = self.username.get()
Then you can just print them
def start_hashtag(self):
print(dictionary['username'],dictionary['password'])
There are few issues in your code:
should not call self.password = self.password.get() and self.username = self.username.get() just after self.username and self.password are created because they will be both empty strings and override the references to the two Entry widgets.
username and password are instance variables of StartPage, so they cannot be access by StartPage.username and StartPage.password
two __init__() function definitions in PageOne class
when switching frame, the previous frame is destroyed. So username and password will be destroyed as well and cannot be accessed anymore.
You can use instance of SampleApp to store the username and password, so they can be accessed by its child frames:
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
tk.Button(self, text="Login", command=self.login).pack()
def login(self):
# store the username and password in instance of 'SampleApp'
self.master.username = self.username.get()
self.master.password = self.password.get()
# switch to PageOne
self.master.switch_frame(PageOne)
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
if filename:
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
# get username and password from instance of SampleApp
print(self.master.username, self.master.password)

Tkinter Multiple GUI

Hey I am having a problem during connecting two Gui together as when button pressed i want the tkinter to open another gui from another file.
File one contains the frontend dashboard and when you click on the teacher than click on login it gives me an error saying.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: __init__() missing 1 required positional argument: 'master'
this is the main page Source Code:
from tkinter import *
from login import *
import tkinter as tk
from tkinter import ttk
class Frontend(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title('Portal') # set the title of the main window
self.geometry('300x300') # set size of the main window to 300x300 pixels
# this container contains all the pages
container = tk.Frame(self)
container.pack(side='top', fill='both', expand=True)
container.grid_rowconfigure(0, weight=1) # make the cell in grid cover the entire window
container.grid_columnconfigure(0,weight=1) # make the cell in grid cover the entire window
self.frames = {} # these are pages we want to navigate to
for F in (Dashboard, Teacher, Student): # for each page
frame = F(container, self) # create the page
self.frames[F] = frame # store into frames
frame.grid(row=0, column=0, sticky='nsew') # grid it to container
self.show_frame(Dashboard) # let the first page is Dashboard
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
class Dashboard(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = ttk.Label(self, text="Main Screen", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = ttk.Button(self, text="Teacher",
command=lambda: controller.show_frame(Teacher))
button.pack()
button1 = ttk.Button(self, text="Student",
command=lambda: controller.show_frame(Student))
button1.pack()
class Teacher(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Teacher Login", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#logo = ImageTk.PhotoImage(Image.open('logo.png'))
button = ttk.Button(self, text="Login", command=LoginFrame)
button.pack()
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(Dashboard))
button1.pack()
class Student(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Student Login", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(Dashboard))
button.pack()
def main():
root = Frontend()
root.mainloop()
if __name__=='__main__':
main()
Login source code:
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
self.logbtn = Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clicked(self):
# print("Clicked")
username = self.entry_username.get()
password = self.entry_password.get()
# print(username, password)
if username == "admin" and password == "admin123":
tm.showinfo("Login info", "Welcome Admin")
else:
tm.showerror("Login error", "Incorrect username")
def main():
root = Tk()
page = LoginFrame(root)
root.mainloop()
if __name__=='__main__':
main()
Thanks

Why my code is not working?

New to tkinter, but as of now, I don't know why my code keeps returning Failed instead of passed.
import tkinter as tk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.user_Label = tk.Label(self, text="Username")
self.pass_entry = tk.Entry(self)
self.pass_Label = tk.Label(self, text="Password")
self.login = tk.Button(self, text="Login", foreground="black", command=self.on_button)
#Packing
self.user_Label.pack()
self.entry.pack()
self.pass_Label.pack()
self.pass_entry.pack()
self.login.pack()
def on_button(self):
if self.entry and self.pass_entry == "hello":
print("passed")
else:
print("Failed")
app = GUI()
app.mainloop()
It does not work because you need to use the following to get the value of the password entered:
self.pass_entry.get()
Consequently, you should have:
if self.entry.get() and self.pass_entry.get() == "hello":
As a side note. If you have password Entry widget, better to do it as follows:
self.pass_entry = tk.Entry(self, show="*")

Categories

Resources