i'm new to tkinter and wanted to change an already existing piece of code I made into GUI. The piece of code below is a username and password system. The thing I need help with is that I can not figure out how to get a new box or to remove the widgets of the gui. Nothing is wrong with the code below but I wanted to show you as it shows you how I've coded it and how to make a new box based on this code.
Btw I am in python 3.5.1 and on windows 10.
import tkinter
from tkinter import *
import tkinter.messagebox as box
import time
def dialog1():
username=entry1.get()
password = entry2.get()
if (username == 'Noel' and password == 'Music quiz'):
box.showinfo('info','You may now enter the Music quiz')
else:
box.showinfo('info','Invalid Login')
window = Tk()
window.title('Music quiz')
window.geometry("300x125")
window.wm_iconbitmap('Favicon.ico')
frame = Frame(window)
Label1 = Label(window,text = 'Username:')
Label1.pack()
entry1 = Entry()
entry1.pack()
Label2 = Label(window,text = 'Password: ')
Label2.pack()
entry2 = Entry()
entry2.pack()
Here is edited code that I think will do what you have asked. Explanations are in the code in the form of comments.
import tkinter
from tkinter import *
import tkinter.messagebox as box
import time
def dialog1():
username=entry1.get()
password = entry2.get()
if (username == 'Noel' and password == 'Music quiz'):
box.showinfo('info','You may now enter the Music quiz')
loginframe.destroy() #remove the login frame
##code to create the quiz goes here##
else:
box.showinfo('info','Invalid Login')
window = Tk()
window.title('Music quiz')
window.geometry("300x125")
window.wm_iconbitmap('Favicon.ico')
loginframe = Frame(window) #create an empty frame for login
loginframe.pack() #put the empty frame into the window
#all elements below are put into the 'loginframe' Frame
Label1 = Label(loginframe,text = 'Username:')
Label1.pack()
entry1 = Entry(loginframe)
entry1.pack()
Label2 = Label(loginframe,text = 'Password: ')
Label2.pack()
entry2 = Entry(loginframe)
entry2.pack()
donebttn = Button(loginframe, text='Done',
command=dialog1) #create a button to continue
donebttn.pack() #display that button
mainloop()
Related
So, I've been trying to bind the enter key to press the button I have in this python program -- yes I've seen the numerous other questions related to this, but none of their code worked with this program for whatever reason. Posting code below to see if anyone has a good solution.
The below code does everything as expected -- it will pull up the GUI, show the goofy jar-jar picture, the button, and the entry fields with the prefilled text, but the enter key on my keyboard will not produce a result as it happens when I press the button with the mouse.
import tkinter as tk
from PIL import Image, ImageTk, ImageTransform
from tkinter.filedialog import askopenfile
root = tk.Tk()
class guiMenu:
def __init__(self, master):
myFrame = tk.Frame(master)
# logo
logo = Image.open('jar.jpg')
logo2 = logo.resize((200, 200), Image.ANTIALIAS)
logo2 = ImageTk.PhotoImage(logo2)
self.logo_label = tk.Label(image=logo2)
self.logo_label.image = logo2
self.logo_label.grid(column=1, row=0)
# instructions
self.instructions = tk.Label(master,
text="Input your email address and password to extract email attachments.\n "
"You should also select the folder you wish the attachments to reach.")
self.instructions.grid(columnspan=3, column=0, row=3)
# store the user login info in variables
def storeUserLogin():
clientEmailInput = self.emailEntry.get()
clientPasswordInput = self.passwordEntry.get()
print(clientEmailInput, clientPasswordInput)
# delete email prefill on click
def onEmailClick(event):
self.emailEntry.configure()
self.emailEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.emailEntry.unbind('<Button-1>', self.on_click_id)
# delete pw prefill on click
def onPWClick(event):
self.passwordEntry.configure()
self.passwordEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.passwordEntry.unbind('<Button-1>', self.on_click_id2)
# email entry box
self.emailEntry = tk.Entry(master, width=50)
# emailEntry = tk.StringVar(None)
# emailEntry.set("Email Address")
self.emailEntry = tk.Entry()
self.emailEntry.insert(0, "Email Address")
self.emailEntry.configure()
self.emailEntry.grid(column=1, row=1)
# on-click function
self.on_click_id = self.emailEntry.bind('<Button-1>', onEmailClick)
# enter key function
def enterFunction(event=None):
master.bind('<Return>', lambda event=None, loginButton.invoke())
# password entry box
self.passwordEntry = tk.Entry()
self.passwordEntry.insert(0, "Password")
self.passwordEntry.grid(column=1, row=2)
# on click function
self.on_click_id2 = self.passwordEntry.bind('<Button-1>', onPWClick)
# button to login
def loginButton():
self.loginButtonText = tk.StringVar()
self.loginButton = tk.Button(master, textvariable=self.loginButtonText, font="Arial",
commands=lambda: [storeUserLogin(), enterFunction()],
width=5, height=2,
bg="white", fg="black")
self.loginButtonText.set("LOGIN")
self.loginButton.grid(column=1, row=4)
self.canvas = tk.Canvas(root, width=600, height=250)
self.canvas.grid(columnspan=3)
g = guiMenu(root)
root.mainloop()
You're Binding the loginButton function in another function which is never called and you are writing the OOPs wrong here. You shouldn't define your functions in init function.Here is some changes that i made in your code. I am not good at explaining but i hope this will help. I wrote reasons too in code where i change the code.
import tkinter as tk
from PIL import Image, ImageTk, ImageTransform
from tkinter.filedialog import askopenfile
root = tk.Tk()
class guiMenu:
def __init__(self, master):
#definr master in Class so we can use it from entire class
self.master = master
myFrame = tk.Frame(master)
# logo
logo = Image.open('Spitball\Spc.jpg')
logo2 = logo.resize((200, 200), Image.ANTIALIAS)
logo2 = ImageTk.PhotoImage(logo2)
self.logo_label = tk.Label(image=logo2)
self.logo_label.image = logo2
self.logo_label.grid(column=1, row=0)
#Create Email Entry box (we are creating Email and Password entry box when class is initialize)
self.emailEntry = tk.Entry(master, width=50)
self.emailEntry.insert(0, "Email Address")
# emailEntry = tk.StringVar(None)
# emailEntry.set("Email Address")
# self.emailEntry = tk.Entry() # You should not create two entry boxes with same name
# self.emailEntry.configure() # We dont need to configure email entry here
#Create Password Entry box (we are creating Email and Password entry box when class is initialize)
self.passwordEntry = tk.Entry()
self.passwordEntry.insert(0, "Password")
#Grid the email and password entry box.Here email entry box will display first beacuse we grid it first.
self.emailEntry.grid(column=1, row=1)
self.passwordEntry.grid(column=1, row=2)
# instructions
self.instructions = tk.Label(master,
text="Input your email address and password to extract email attachments.\n "
"You should also select the folder you wish the attachments to reach.")
self.instructions.grid(columnspan=3, column=0, row=3)
#Create Login Button
self.loginButtonText = tk.StringVar()
self.loginButton = tk.Button(self.master, textvariable=self.loginButtonText, font="Arial",
command=self.storeUserLogin,
width=5, height=2,
bg="white", fg="black")
# I dont see here the use of Canvas so i commented out it.
# self.canvas = tk.Canvas(self.master, width=600, height=250)
# on-click function
self.on_click_id = self.emailEntry.bind('', self.onEmailClick)
# on click function
self.on_click_id2 = self.passwordEntry.bind('', self.onPWClick)
#Bind enter key with loginButtonFunc
self.master.bind('',self.loginButtonFunc)
def storeUserLogin(self):
# store the user login info in variables
clientEmailInput = self.emailEntry.get()
clientPasswordInput = self.passwordEntry.get()
print(clientEmailInput, clientPasswordInput)
# delete email prefill on click
def onEmailClick(self,event):
self.emailEntry.configure()
self.emailEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.emailEntry.unbind('', self.on_click_id)
# delete pw prefill on click
def onPWClick(self,event):
self.passwordEntry.configure()
self.passwordEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.passwordEntry.unbind('', self.on_click_id2)
# button to login
def loginButtonFunc(self,event=None):
self.loginButtonText.set("LOGIN")
self.loginButton.grid(column=1, row=4,pady=5)
# self.canvas.grid(columnspan=3)
g = guiMenu(root)
root.mainloop()
I'm working on a python assignment and this is where I got so far. I'm stuck and cannot execute the application. I'm making a calculator that scores the average and gives a grade letter. I was looking into my professor's video and there was "import tkinter.messagebox as tkm" but Im not sure how to implement this in the code.
this is my code:
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
window = tk.Tk()
window.geometry('300x300')
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
Button1 = tk.Button(window, text="quit",
command=window.destroy)
messagebox can help to create fast small message windows.
The usage is very simple, just implement this in your code:
from tkinter import messagebox
In you case:
from tkinter import messagebox as tkm
Then:
messagebox.function(title,message,options)
In your case:
tkm.function(title,message,options)
The functions are:
showinfo(): for showing some relevant informations.
showwarning(): for displaying a warning to the user.
showerror(): for displaying an error message.
askquestion(): for asking a yes/no question to the user.
askokcancel(): confirm the user’s action regarding some application
activity.
askyesno(): for asking a yes/no question about a user action.
askretrycancel(): for asking the user about doing a specific task again.
The options are:
default: this option is used to specify the default button like
ABORT, RETRY, or IGNORE in the message box.
parent: this option is used to specify the window on top of which
the message box is to be displayed.
The code needs just some improvements:
pack() the two buttons (as to display them)
add window.mainloop() at the end of your code (this is why is does not start)
There are multiple problems in your code. First, you define window two times. The second time, you just override your frist instance of window, so just leave that out.
Then you are not packing your Buttons, which means they will not be shown in your window. Lastly, you are missing the most important part of your Tkinter Application, which is to start the applications mainloop, which makes the window pop up and tells Tkinter to start listening for your mouse and keyboard interaction with the window and do something with it. This is called an event loop and is the main component of every graphical user interface. You start the eventloop by calling .mainloop() on your instance of tk.Tk, which is your window variable.
Lastly, it is unclear from your text what you actually want to do with the Messagebox.
I assume that you want to use the message box to display the result of your calculate function, since right now it doesn't do anything.
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
message = 'Your result is ' + lettergrade
tkm.showinfo(title='Result', message=message)
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
button2.pack()
Button1 = tk.Button(window, text="quit",
command=window.destroy)
Button1.pack()
window.mainloop()
So over here I am trying to make a little python-tkinter program which will store your passwords of your apps in files. However, when I try to make the second screen open, I get this error:
TypeError: 'Toplevel' object is not callable
Here is the code:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
global screen2
screen2 = Toplevel(root)
screen2.title("Main Page")
screen2.geometry("260x230")
screen2.resizable("False","False")
Label(screen2, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root
global code
global code_request
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
code_request = StringVar()
label1 = Label(root, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(text="").pack()
enter_code = Entry(root, width="20", textvariable=code_request)
enter_code.pack()
Label(text="").pack()
continue_button = Button(root, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
Unrelated to your question, but seeing your window names makes me think you don't want to use Toplevel at all. That's only needed when you want 2 active windows, but I suspect you want to use one window just to check the password, then close it and open a second, "main" window, right? If so you need to reconfigure the root window instead of using Toplevel to open a new window. Like this:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
frame1.destroy() # remove all the pw check stuff
root.title("Main Page") # rename window
Label(root, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root, code, code_request, frame1
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
frame1 = Frame(root) # create a Frame to hold pw check components
frame1.pack()
code_request = StringVar()
label1 = Label(frame1, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(frame1, text="").pack()
enter_code = Entry(frame1, width="20", textvariable=code_request)
enter_code.pack()
Label(frame1, text="").pack()
continue_button = Button(frame1, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
I have been working on a login page in Tkinter for fun, but I am unable to make a function that checks the entries and compares them to a specific input. Also, the code adds a messagebox and calls a function every time I exit the window.
My code is:
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Login")
def makeUname(d):
if messagebox.askyesno("Submit?", "Is this correct?"):
global password
username = uname.get()
uname.grid_forget()
return password
def makePasswd(d):
if messagebox.askyesno("Submit?", "Is this correct?"):
global username
password = uname.get()
passwd.grid_forget()
return username
def button():
makeUname("")
makePasswd("")
quitbutt.grid_forget()
uname = Entry(root)
uname.grid(row=1, column=1)
passwd = Entry(root, show="*")
passwd.grid(row=2, column=1)
quitbutt = Button(root, text="Login", command=button)
quitbutt.grid(row=3, column=1, columnspan=2, sticky='nesw')
root.mainloop()
makeUname("")
makePasswd("")
if(username == "username" and password == "password"):
messagebox.showwarning("Warning", "Sorry, this isn't programmed yet.")
else:
messagebox.showwarning("Nope", "Nope. Nice try.")
Can someone help me with my code? Should I use a different setup or method?
There was many problem so I changed all to make it simpler.
I added comments in code to explain some elements.
from tkinter import *
from tkinter import messagebox
# --- functions ---
def button():
# use global variable (instead of local variables)
# to keep username, password outside function and keep after closing window
global username
global password
username = uname.get()
password = passwd.get()
#print('button:', username, password)
if username == "username" and password == "password":
messagebox.showwarning("Warning", "Sorry, this isn't programmed yet.")
root.destroy() # close window
else:
messagebox.showwarning("Nope", "Nope. Nice try.")
# window still open
# --- main ---
# default values at start
# Someone can exit window without using Button
# and it would not create this variables in button()
username = ""
password = ""
root = Tk()
root.title("Login")
uname = Entry(root)
uname.grid(row=1, column=1)
passwd = Entry(root, show="*")
passwd.grid(row=2, column=1)
quitbutt = Button(root, text="Login", command=button)
quitbutt.grid(row=3, column=1, columnspan=2, sticky='nesw')
# start program (start engine, display window, (re)draw widgets, handle events, get events from system (keyboard, mouse), send events to widgets)
root.mainloop()
# after closing window this variables still have values from window
print("after mainloop:", username, password)
I have no idea that how to make a program in python the makes a login input, an input area, and a submit button and saves to these variables:
e_id = #email id
pw = # password
sv = #the input
I have made a code that seems complex but do the thing. The function get will run on submit button and will define the variables:
As you said, the input is converted into a dropdown list
import tkinter as tk
root = tk.Tk()
tk.Label(text="Email: ").grid(row=0,column=0)
tk.Label(text="Password: ").grid(row=1,column=0)
tk.Label(text="Server: ").grid(row=2,column=0)
e = tk.Entry()
p = tk.Entry(show="*")
var = tk.StringVar()
var.set("Server 1")
panel = tk.OptionMenu(root,var,"Server 1","Server 2","Server 3")
panel.config(width=15)
e.grid(row=0,column=1)
p.grid(row=1,column=1)
panel.grid(row=2,column=1)
def get():
e_id = e.get()
pw = p.get()
sv = panel.get()
print(e_id, pw, sv)
tk.Button(root, text="Submit", command = get).grid(column=1)
root.resizable(False,False)
root.mainloop()
Output:
The entries are filled mannually