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()
Related
I created a menu item and want to run a function within that menu which will run a simple calculation based on a entry. When I run the code in my terminal, I can see my window and the menu item with the entry widget. But, I don't see anything and result from my function. I don't get an error from the terminal. Below is my code. Where did I mess in my code?
from tkinter import *
root = Tk()
root.title(" My calculator")
root.geometry("400x400")
# Defining calculator 1 function
def calculator_1():
# creating an entry
frame1.pack(fill="both",expand=1)
e1 =Entry(frame1)
e1.pack(pady=5)
# Defining the formula function
def formula():
res = (int(e1.get()) + 1)
myText.set(res)
# creating a calculate button
my_button = Button(frame1, text="Click to calculate", command=formula)
my_button.pack(pady=5)
myText=StringVar()
result=Label(frame1, text=" your results is ", textvariable =myText)
result.pack(pady=5)
label_result =Label(frame1, text= "Your result is")
label_result.pack(pady=5)
# Define Main menu
my_menu = Menu(root)
root.config(menu=my_menu)
#create menu items
math_menu = Menu(my_menu)
my_menu.add_cascade(label="MathCards",menu=math_menu)
math_menu.add_command(label="Calculator 1",command=calculator_1)
math_menu.add_separator()
math_menu.add_command(label="Exit", command=root.quit)
# Creating a frame
frame1 = Frame(root, width =400, height=400)
root.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()
This is my first attempt at tkinter. I was using this tutorial, code below, where a user input a number, and with a button generate a result at another window.
import tkinter as tk
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()
entry1 = tk.Entry (root)
canvas1.create_window(200, 140, window=entry1)
def getSquareRoot ():
x1 = entry1.get()
label1 = tk.Label(root, text= float(x1)**0.5)
canvas1.create_window(200, 230, window=label1)
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot)
canvas1.create_window(200, 180, window=button1)
root.mainloop()
How can I do this directly, without the button? I.e., Enter number > result is generated immediately?
How about using bind for this effect, when you press a binded key, the function gets called and executed.
Here is an example:
import tkinter as tk
root = tk.Tk()
entry1 = tk.Entry(root)
entry1.pack(pady=(20, 0), padx=10)
label1 = tk.Label(root)
def getSquareRoot(event=None):
root.after(1000,getSquareRoot)
x1 = entry1.get()
try:
sqrt = float(x1)**0.5
except:
sqrt = ''
label1.config(text=sqrt)
label1.pack()
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot)
button1.pack(pady=(0, 20))
entry1.bind('<Return>', getSquareRoot)
root.after(5000,getSquareRoot)
root.mainloop()
If you press the Enter key at the entry widget, it will generate the output for you, without hitting any buttons.
If you want to display Entry widget contents without using the keyboard then use a mouse key press.
entry1.bind('<Double-Button-1>', getSquareRoot)
or
entry1.bind('<Button-3>', getSquareRoot)
image for that
I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again.
from tkinter import *
from tkinter import messagebox
def top():
if entry1.get() == "333":
log.destroy()
root.deiconify()
else:
messagebox.showerror("error", "try again")
root = Tk()
root.geometry("300x300")
log = Toplevel(root)
log.geometry("200x200")
label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)
label1.pack()
entry1.pack()
button1.pack(side="bottom")
lab = Label(root, text="welcome bro").pack()
root.withdraw()
root.mainloop()
You need to make the log window the parent of the dialog:
messagebox.showerror("error", "try again", parent=log)
By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.
With hint from #furas this how to implement this:
create another function to the call it when the entry doesn't match and use grab_set method for the Toplevel window tp.grab_set().You can add your customarised image to the Toplevel window as well as message to display in the box(here: i use label to depict that)
from tkinter import *
from tkinter import messagebox
def dialog(): # this function to call when entry doesn't match
tp = Toplevel(log)
tp.geometry("300x100")
tp.title('error')
tp.grab_set() # to bring the focus to the window for you to close it
tp.resizable(width=False, height=False)
l = Label(tp, text="try again\n\n\n\n add your customarize image to the window")
l.pack()
def top():
if entry1.get() == "333":
log.destroy()
root.deiconify()
else:
dialog() # being called here
root = Tk()
root.geometry("300x300")
log = Toplevel(root)
log.geometry("200x200")
label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)
label1.pack()
entry1.pack()
button1.pack(side="bottom")
lab = Label(root, text="welcome bro").pack()
root.withdraw()
root.mainloop()
im trying to make some code, so that when you type your name into the input box and hit the ok button, your name is then retrieved, and used as the text in a picture, my code is below.
from Tkinter import *
c = Canvas(width=500, height=500, bg='white')
c.pack(expand=YES, fill=BOTH)
master = Tk()
var = StringVar(master)
var.set("one") # initial value
option = OptionMenu(master, var, "one", "two", "three", "four")
option.pack()
#
def ok():
print "value is", var.get()
master.quit()
user = var.get() ##### this is what im struggling with
button = Button(master, text="OK", command=ok)
user = var.get()
c.create_text(200,470,text="by "+user, anchor=N, justify=CENTER) # credits
mainloop()
I think I know what you want to do? I have made some code which you enter your name into an entry box, when you hit ok your name is made into a label on the same tk window as the entry box.
Here is the code:
from Tkinter import *
master = Tk()
label = Label(text='please enter you name:')
label.pack()
entry = Entry()
entry.pack()
def ok():
type = ('Times', 20)
name = entry.get()
Label(text = name, font = type).pack()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
give it a try and tell me if this is what you wanted or not!