Nothing coming up in a GUI (Tkinter) window - python

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()

Related

How to add a button in a topLevel window?

This code is supposed to ask login information from the user. Then when it enters the wrong details, it will do a popup (loginErrorWdw) with a label and a button. The button there will exit the program when pressed.
I'm trying to get the button from loginErrorWdw to appear in that window but it won't. Here's my whole block of code.
from tkinter.ttk import *
from tkinter import messagebox
import tkinter as tk
import sys
import os
class Login(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
self.loginWidgets()
def loginWidgets(self):
self.userlbl = Label(self, text="Enter username: ")
self.userlbl.grid()
self.unEntry = Entry(self)
self.unEntry.grid(row=0, column=1, sticky=W)
self.pwlbl = Label(self, text="Enter password: ")
self.pwlbl.grid(row=1, column=0, sticky=W)
self.pwEntry = Entry(self, show="*")
self.pwEntry.grid(row=1, column=1, sticky=W)
self.submitBtn = Button(self, text="LOGIN", command=self.checkLogin)
self.submitBtn.grid(row=2, column=1, sticky=W)
def loginErrorWdw(self):
err = tk.Toplevel(self)
err.title("Error")
l = tk.Label(err, text="Invalid login details! The program will exit.")
l.pack(side="top", expand=False, padx=20, pady=20)
btn=tk.Button(err, text="Ok", command=self.exitBtn)
def exitBtn(self):
os._exit(0)
#change def position
def mainWdw(self):
messagebox.showinfo('Main window','Message pop up')
def checkLogin(self):
user = self.unEntry.get()
pw = self.pwEntry.get()
if user == "admin":
if pw == "lbymf1d":
self.mainWdw()
else:
self.loginErrorWdw()
else:
self.loginErrorWdw()
# un = admin, pw = lbymf1d
#window = var
window = Tk()
window.title("Login UI")
# window size
window.geometry('700x300')
login = Login(window)
# loop for window
window.mainloop()
You forgot about btn.pack()
This is way without errors:
from tkinter.ttk import *
from tkinter import messagebox
import tkinter as tk
import sys
# import os
class Login(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.loginWidgets()
def loginWidgets(self):
self.userlbl = Label(self, text="Enter username: ")
self.userlbl.grid()
self.unEntry = Entry(self)
self.unEntry.grid(row=0, column=1, sticky="W") # sticky must be string
self.pwlbl = Label(self, text="Enter password: ")
self.pwlbl.grid(row=1, column=0, sticky="W")
self.pwEntry = Entry(self, show="*")
self.pwEntry.grid(row=1, column=1, sticky="W")
self.submitBtn = Button(self, text="LOGIN", command=self.checkLogin)
self.submitBtn.grid(row=2, column=1, sticky="W")
def loginErrorWdw(self):
err = tk.Toplevel(self)
err.title("Error")
l = tk.Label(err, text="Invalid login details! The program will exit.")
l.pack(side="top", expand=False, padx=20, pady=20)
btn = tk.Button(err, text="Ok", command=self.exitBtn)
btn.pack() # Draw it
def exitBtn(self):
sys.exit(0) # Exit
# change def position
def mainWdw(self):
messagebox.showinfo('Main window', 'Message pop up')
def checkLogin(self):
user = self.unEntry.get()
pw = self.pwEntry.get()
if user == "admin":
if pw == "lbymf1d":
self.mainWdw()
else:
self.loginErrorWdw()
else:
self.loginErrorWdw()
# un = admin, pw = lbymf1d
# window = var
window = tk.Tk()
window.title("Login UI")
# window size
window.geometry('700x300')
login = Login(window)
# loop for window
window.mainloop()

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()

StringVar().get() not returning string

I am trying to get the input of what page number the user wants. They should type in a number, and click the submit button. To test it, I just want to print whatever they typed and then close the window. I've been following: http://effbot.org/tkinterbook/entry.htm as a guide, but I am stumped.
Why does
print(temp)
not print out a number to console?
right now it prints out:
<bound method IntVar.get of <tkinter.IntVar object at 0x000001FBC85353C8>>
I've cleaned up the code a little bit:
import sys
from file import *
from page import *
from view import View
import tkinter as tk
from tkinter import *
class ViewGui:
def __init__(self):
#Included in the class, but unrelated to the question:
self._file = File("yankee.txt", 25)
self.pages = self._file.paginate()
self.initial_list = self.pages[0].readpage(self._file.fo)
self.initial_string = ''.join(self.initial_list)
# Create root
self.root = Tk()
self.root.wm_title("yankee.txt - page 1")
# Create frame for buttons
self.bframe = Frame(self.root)
self.bframe.pack(side=BOTTOM, fill=X)
self.tbutton = tk.Button(self.bframe, text="Top", command=lambda a="top": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.bbutton = tk.Button(self.bframe, text="Bottom", command=lambda a="bottom": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.ubutton = tk.Button(self.bframe, text="Up", command=lambda a="up": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.dbutton = tk.Button(self.bframe, text="Down", command=lambda a="down": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.pbutton = tk.Button(self.bframe, text="Page", command=lambda a="page": self.pageclicks()).pack(side=LEFT, expand=1, fill=X)
self.qbutton = tk.Button(self.bframe, text="Quit", command=quit).pack(side=LEFT, expand=1, fill=X)
# Create and pack Text
self.T = Text(self.root, height=35, width=60, wrap=NONE)
self.T.pack(side=TOP, fill=X)
# Create and pack Scrollbar
self.S = Scrollbar(self.root, orient=HORIZONTAL, command=self.T.xview)
self.S.pack(side=BOTTOM, fill=X)
# Attach Text to Scrollbar
self.T.insert('1.0', self.initial_string)
self.T.config(xscrollcommand=self.S.set, state=DISABLED)
self.S.config(command=self.T.xview)
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = Tk()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop.entrytext = IntVar()
Entry(pop, textvariable=pop.entrytext).pack()
pop.submitbuttontext = StringVar()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
pop.cancelbuttontext = StringVar()
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, a):
print('submitted is getting called')
temp = (a.entrytext.get)
print(temp)
def clicks(self, a):
print("you clicked clicks with the " + a)
self.root.wm_title(self._file.filename + " - Page " + self._file.buttonHandler(a))
if __name__ == "__main__":
vg = ViewGui()
vg.root.mainloop()
When you create a new window you should not use Tk(), you must use tk.Toplevel()
Must change:
pop = Tk()
to
pop = tk.Toplevel()
You should also use get(), not just get. Must change:
temp = (a.entrytext.get)
to
temp = a.entrytext.get()
Code:
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = tk.Toplevel()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop.entrytext = IntVar()
Entry(pop, textvariable=pop.entrytext).pack()
pop.submitbuttontext = StringVar()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
pop.cancelbuttontext = StringVar()
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, a):
print('submitted is getting called')
temp = a.entrytext.get()
print(temp)
Made changes to these two methods and now it is working.
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = Tk()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop._entry = Entry(pop)
pop._entry.pack()
pop._entry.focus_set()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, _pop):
temp = _pop._entry.get()
print(temp)
_pop.destroy()

Tkinter multiple command and def

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()

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