Tkinter multiple command and def - python

I am writing a Password code. I need a way to put to commands into one button so that it will destroy the window and get the username and password when I click the login button. I have looked through this site and non of the methods work for me so I need clarity on what I need to do to fix this.
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_1 = Label(self, text="Username")
self.label_2 = Label(self, text="Password")
self.entry_1 = Entry(self)
self.entry_2 = Entry(self, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
***def destroy(self):
self.destroy()
self.logbtn = Button(self, text="Login", command = self._login_btn_clickked,)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clickked(self):
username = self.entry_1.get()
password = self.entry_2.get()
if username == "jake" and password == "hey":
tm.showinfo("Login info", "Welcome Jake")
master=Tk()
def login2():
tm.showinfo("Logging in", "Logging In...")
b = Button(master, text="Enter GUI", command=login2)
b.pack()
else:
tm.showerror("Login error", "Incorrect username")***
root = Tk()
lf = LoginFrame(root)
root.mainloop()

You should never call Tk() more than once in your program. If you need additional windows, use Toplevel().
However, in your case you don't need that either. You are on the right track of destroying the frame, now you just need to initiate a new frame. We can put that logic into a Tk class:
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
self.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")
lbl = tk.Label(self, text='You made it to the main application')
lbl.pack()
if __name__=="__main__":
app=Mainframe()
app.mainloop()

Related

Im not getting any prompt window while executing the below script

from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text="Enter password")
self.instruction.grid(row=0, cloumn=0, cloumnspan=2, sticky=W)
self.password = Entry(self)
self.password.grid(row=1, column=1, sticky=W)
self.submit_button = Button(self, text="submit", command=self.reveal)
self.submit_button.grid(row=2, column=0, sticky=W)
self.text = Text(self, width=35, height=5, wrap=WORD)
self.text.grid(row=3, column=0, columnspan=2, sticky=W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have access to something special"
else:
message = "Access Denined"
self.text.insert(0.0, message)
root = Tk()
menubar = Menu(root)
root.geometry("450x450+500+300")
root.title("Change Creation")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Close", command = close)
menubar.add_cascade(label="File", menu=filemenu)
root.title("Password")
root.geometry("250x150")
app = Application(root)
root.mainloop()
while execution of the above code, I'm not getting any prompt or any error.Help me out in finding the solution
You have several indention errors and typos.
I am not sure how you are not getting errors as I had to fix at least 3 errors while trying to run your code. If you are using Python's default IDLE then I would suggest upgrading to something like PyCharm or Eclipse Pydev. They will provide proper traceback errors for debugging.
I have cleaned up you code. Make sure you check spelling. You had cloumn instead of column and cloumnspan instead of columnspan. command = close will cause an error as no method or function exist called close.
from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text="Enter password")
self.instruction.grid(row=0, column=0, columnspan=2, sticky=W)
self.password = Entry(self)
self.password.grid(row=1, column=1, sticky=W)
self.submit_button = Button(self, text="submit", command=self.reveal)
self.submit_button.grid(row=2, column=0, sticky=W)
self.text = Text(self, width=35, height=5, wrap=WORD)
self.text.grid(row=3, column=0, columnspan=2, sticky=W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have access to something special"
else:
message = "Access Denined"
self.text.insert(0.0, message)
root = Tk()
menubar = Menu(root)
root.geometry("450x450+500+300")
root.title("Change Creation")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Close")
menubar.add_cascade(label="File", menu=filemenu)
root.title("Password")
root.geometry("250x150")
app = Application(root)
root.mainloop()

Nothing coming up in a GUI (Tkinter) window

I am writing a code for a login system using tkinter and for some reason when I run the code there are no error messages and a window pops up but without the title, buttons or labels I need.
from tkinter import *
import tkinter.messagebox
frame = Tk()
def adminlogincheck(self, master):
frame = Frame(master)
frame.pack()
if username == '123key' and password == 'key123':
accept = Label(frame, text='Login Successful')
else:
decline = Label(frame, text='Login incorrect')
mainloop()
def adminselect(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="Cancel", fg="red", command=quit)
self.button.pack(side=LEFT)
self.slogan = Button(frame, text="Proceed", command=self.adminlogin)
self.slogan.pack(side=LEFT)
mainloop()
def adminlogin(self, master):
frame = Frame(master)
frame.pack()
username_entry = Entry(frame)
password_entry = Entrey(frame)
confirm = Button(frame, text='Login', command = adminlogincheck)
loginquit = Button(frame, text='Cancel', command=quit)
mainloop()
I will add more after the login system works but does anyone know why no buttons or labels appear?
There's enough in your request to see what you're trying to accomplish, but there are many issues with the code. Here is a working model of what you appear to be working toward...
from tkinter import *
import tkinter.messagebox
class Admin:
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
self.username = StringVar()
self.password = StringVar()
def logincheck(self):
self.clearframe()
if self.username.get() == '123key' and self.password.get() == 'key123':
accept = Label(self.frame, text='Login Successful')
accept.pack(side=LEFT)
else:
decline = Label(self.frame, text='Login incorrect')
decline.pack(side=LEFT)
def select(self):
self.clearframe()
self.button = Button(self.frame, text="Cancel", fg="red", command=quit)
self.button.pack(side=LEFT)
self.slogan = Button(self.frame, text="Proceed", command=self.adminlogin)
self.slogan.pack(side=LEFT)
def login(self):
self.clearframe()
username_entry = Entry(self.frame, textvariable=self.username)
username_entry.pack()
password_entry = Entry(self.frame, textvariable=self.password)
password_entry.pack()
confirm = Button(self.frame, text='Login', command = self.logincheck)
confirm.pack()
loginquit = Button(self.frame, text='Cancel', command=quit)
loginquit.pack()
def clearframe(self):
# Destroy all children of the class's frame.
for child in self.frame.winfo_children():
child.destroy()
root = Tk()
admin = Admin(root)
admin.login()
mainloop()

How to update label on tkinter

I would like to update a label once I press one of the buttons.
Here is my code - I added a label (caled label1), now I have two issues:
It presents some gibberish
How do I update the label with text right when the user is pressing the Browse button?
from tkinter import *
import threading
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.var = IntVar()
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text="Exit", command=self.client_exit)
startButton = Button(self, text="Browse", command=self.start_Button)
label1 = Label(self, text=self.lable_1)
quitButton.grid(row=0, column=0)
startButton.grid(row=0, column=2)
label1.grid(row=1, column=0)
def client_exit(self):
exit()
def lable_1(self):
print('starting')
def start_Button(self):
def f():
print('Program is starting')
t = threading.Thread(target=f)
t.start()
root = Tk()
root.geometry("250x50")
app = Window(root)
root.title("My Program")
root.mainloop()
Use self.label['text'] to change text
(Minimal?) Working example:
import tkinter as tk
class Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
# tk.Frame.__init__ creates self.master so you don't have to
#self.master = master
self.init_window()
def init_window(self):
self.pack(fill=tk.BOTH, expand=1)
quit_button = tk.Button(self, text="Exit", command=root.destroy)
start_button = tk.Button(self, text="Browse", command=self.on_click)
self.label = tk.Label(self, text="Hello")
quit_button.grid(row=0, column=0)
start_button.grid(row=0, column=1)
self.label.grid(row=1, column=0, columnspan=2)
def on_click(self):
self.label['text'] = "Starting..."
root = tk.Tk()
app = Window(root)
root.mainloop()

Python tkinter: How can I ensure only ONE child window is created onclick and not a new window every time the button is clicked?

Currently learning tkinter and have come to a dead end.
Each time I click one of the buttons in my GUI (after typing 'username' and 'password' into the log in screen) a new child window is created and appears. As it should. What I would now like to do is to ensure that only one window is created and any subsequent clicks do not create yet more windows. How could this be done?
from tkinter import *
class Main():
def __init__(self, master):
self.master = master
self.master.title("Main Window")
self.button1 = Button(self.master, text="Click Me 1", command = self.Open1)
self.button1.grid(row=0, column=0, sticky=W)
self.button2 = Button(self.master, text="Click Me 2", command = self.Open2)
self.button2.grid(row=0, column=2, sticky=W)
self.button3 = Button(self.master, text="Close", command = self.Close)
self.button3.grid(row=1, column=0, sticky=W)
def Login(self):
login_win = Toplevel(self.master)
login_window = Login(login_win)
login_window.Focus()
#main_window.Hide()
def Open1(self):
second_window = Toplevel(self.master)
window2 = Second(second_window)
def Open2(self):
third_window = Toplevel(self.master)
window3 = Third(third_window)
def Close(self):
self.master.destroy()
#def Hide(self):
#self.master.withdraw()
#def Appear(self):
#self.master.deiconify()
class Second():
def __init__(self, master):
self.master = master
self.master.title("Child 1 of Main")
self.master.geometry("300x300")
self.button4 = Button(self.master, text="Click Me 1", command = self.Open_Child)
self.button4.grid(row=0, column=0, sticky=W)
def Open_Child(self):
second_child_window = Toplevel(self.master)
window4 = Second_Child(second_child_window)
class Third():
def __init__(self, master):
self.master = master
self.master.geometry("300x300")
self.master.title("Child 2 of Main")
class Second_Child():
def __init__(self, master):
self.master = master
self.master.geometry("400x300")
self.master.title("Child of 'Child 1 of Main'")
class Login():
def __init__(self, window):
self.window = window
self.window.title("Current Library")
Label(self.window, text="Log in to use this program:").grid(row=0, column=0, sticky=W)
self.userbox=Entry(self.window, width=20, bg="light green")
self.userbox.grid(row=1, column=0, sticky=W)
self.passbox=Entry(self.window, width=20, bg="light green")
self.passbox.grid(row=2, column=0, sticky=W)
Button(self.window, text="Submit", width=5, command=self.clicked).grid(row=3, column=0, sticky=W)
def Focus(self):
self.window.attributes('-topmost', 1)
self.window.grab_set()
def clicked(self):
username = self.userbox.get()
password = self.passbox.get()
if password == "password" and username == "username":
self.correct = True
self.window.grab_release()
self.window.destroy()
else:
pass
root_window = Tk()
root_window.iconbitmap(default='transparent.ico')
root_window.geometry("200x100")
main_window = Main(root_window)
main_window.Login()
root_window.mainloop()
Inside the functions which are called when the buttons are clicked could I add an IF statement?: IF window object does not exist then instantiate window object ELSE pass.
def Open1(self):
if window2 == False:
second_window = Toplevel(self.master)
window2 = Second(second_window)
else:
pass
If this is the correct logic then how can I check if a window object has already been created because the above doesn't work as I am referencing the object before it is created?
Many thanks.
Initialize the child window variable in Main's __init__.
self.child_window = None
Then you can check whether it exists in Open1.
def Open1(self):
if not self.child_window:
self.child_window = Second(Toplevel(self.master))
By the way, if you intend for Second to act like its own window, it's a bit awkward that you have to create a Toplevel every time you want to create a Second. Conventionally, you would make Second a subclass of Toplevel, so it can be created on its own. Something like:
class Second(Toplevel):
def __init__(self, master, *args, **kargs):
Toplevel.__init__(self, master, *args, **kargs)
#rest of initialization goes here.
#Use `self` everywhere you previously used `self.master`.
Now you could just do:
def Open1(self):
if not self.child_window:
self.child_window = Second(self.master)

Login to GUI application

I am not familiar with python and creating user login entry window to login to the another window. The problem is that how can I make sure that it is logged in after entering correct username and password. I could go to the window that I want to login by entering the username and password but I think the coding is still not correct. Another thing is that when the login window pop up, if the user just close the window without entering username and password, the program should just quit. However it still continues to go to the window. Below is my code.
Thank you very much in advance
import Tkinter
from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style
class MainWindow(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("AUTO TIPS")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
lbl = Label(self, text="Status")
lbl.grid(sticky=W, pady=4, padx=5)
area = Text(self)
area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)
abtn = Button(self, text="Drive Command", command=win3)
abtn.grid(row=1, column=3)
cbtn = Button(self, text="Tester Manual Control", command=win2)
cbtn.grid(row=2, column=3, pady=4)
dbtn = Button(self, text="Auto Run", command=AutoTIPS)
dbtn.grid(row=3, column=3, pady=4)
obtn = Button(self, text="OK", command=self.parent.destroy)
obtn.grid(row=5, column=3)
####################################################################################################################################################
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
failure_max = 3
passwords = [('Aung', 'Aung')]
def make_entry(parent, caption, width=None, **options):
tk.Label(parent, text=caption).pack(side=tk.TOP)
entry = tk.Entry(parent, **options)
if width:
entry.config(width=width)
entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
return entry
def enter(event):
check_password()
def check_password(failures=[]):
# Collect 1's for every failure and quit program in case of failure_max failures
print(user.get(), password.get())
if (user.get(), password.get()) in passwords:
root.destroy()
print('Logged in')
return
failures.append(1)
if sum(failures) >= failure_max:
root.destroy()
raise SystemExit('Unauthorized login attempt')
else:
root.title('Try again. Attempt %i/%i' % (sum(failures)+1, failure_max))
root = tk.Tk()
root.geometry('300x160')
root.title('Enter your information')
#frame for window margin
parent = tk.Frame(root, padx=10, pady=10)
parent.pack(fill=tk.BOTH, expand=True)
#entrys with not shown text
user = make_entry(parent, "User name:", 16, show='')
password = make_entry(parent, "Password:", 16, show="*")
#button to attempt to login
b = tk.Button(parent, borderwidth=4, text="Login", width=10, pady=8, command=check_password)
b.pack(side=tk.BOTTOM)
password.bind('<Return>', enter)
user.focus_set()
parent.mainloop()
####################################################################################################################################################
def win2():
board = Tkinter.Toplevel()
board.title("Tester Manual Control")
s1Var = Tkinter.StringVar()
s2Var = Tkinter.StringVar()
s3Var = Tkinter.StringVar()
s4Var = Tkinter.StringVar()
s5Var = Tkinter.StringVar()
s6Var = Tkinter.StringVar()
s7Var = Tkinter.StringVar()
s8Var = Tkinter.StringVar()
s1Var.set(" Tester 1")
s2Var.set(" Tester 2")
s3Var.set(" Tester 3")
s4Var.set(" Tester 4")
s5Var.set(" Tester 5")
s6Var.set(" Tester 6")
s7Var.set(" Tester 7")
s8Var.set(" Tester 8")
square1Label = Tkinter.Label(board,textvariable=s1Var)
square1Label.grid(row=1, column=500)
square2Label = Tkinter.Label(board,textvariable=s2Var)
square2Label.grid(row=2, column=500)
square3Label = Tkinter.Label(board,textvariable=s3Var)
square3Label.grid(row=3, column=500)
square4Label = Tkinter.Label(board,textvariable=s4Var)
square4Label.grid(row=4, column=500)
square5Label = Tkinter.Label(board,textvariable=s5Var)
square5Label.grid(row=5, column=500)
square6Label = Tkinter.Label(board,textvariable=s6Var)
square6Label.grid(row=6, column=500)
square7Label = Tkinter.Label(board,textvariable=s7Var)
square7Label.grid(row=7, column=500)
square8Label = Tkinter.Label(board,textvariable=s8Var)
square8Label.grid(row=8, column=500)
####################################################################################################################################################
def win3():
board = Tkinter.Toplevel()
board.title("Drive Command")
codeloadButton = Tkinter.Button(board, text="Code Load", command=win4)
codeloadButton.grid(row=100, column=50)
clearButton = Tkinter.Button(board, text="Clear Dos Table", command=win5)
clearButton.grid(row=500, column=50)
####################################################################################################################################################
def win4():
board = Tkinter.Toplevel()
board.title("Code Load")
####################################################################################################################################################
def win5():
board = Tkinter.Toplevel()
board.title("Clear Dos Table")
####################################################################################################################################################
def main():
root = Tk()
root.geometry("350x300+300+300")
app = MainWindow(root)
root.mainloop()
if __name__ == '__main__':
main()

Categories