I have made a test Code for a school project that was assigned to the class but when i run the code the tkinter buttons load up, however when you press the button on the Maths section(the only one done), the code would crash, any help would be nice.
from tkinter import *
Window_Blank = Tk()
#Advanced Define
def MathA():
answer = input()
answer = int(answer)
print("If A=12*2 and B=15*3, What does AB-B= ")
if answer == 1035:
print("Correct")
else:
print("Incorrect")
print("The Answer was 1035")
def Math():
print(MathA())
return
def Science():
return
def Agriculture():
return
def Geographical():
return
#Basic Define
Frame1 = Frame(Window_Blank)
Frame2 = Frame(Window_Blank)
Frame3 = Frame(Window_Blank)
Frame4 = Frame(Window_Blank)
Button1 = Button(Frame1, text="Math Questions", fg="red", command=Math)
Button2 = Button(Frame2, text="Science Questions", fg="blue", command=Science)
Button3 = Button(Frame3, text="Agricultural Questions", fg="green", command=Agriculture)
Button4 = Button(Frame4, text="Geographical Questions", fg="purple", command=Geographical)
#Framework for the menu
Frame1.grid(row=0, column=0)
Frame2.grid(row=0, column=1)
Frame3.grid(row=0, column=2)
Frame4.grid(row=0, column=3)
Button1.grid(row=1)
Button2.grid(row=2)
Button3.grid(row=3)
Button4.grid(row=4)
Window_Blank.mainloop()
Change this:
def MathA():
print("If A=12*2 and B=15*3, What does AB-B= ")
answer = input()
answer = int(answer)
if answer == 1035:
print("Correct")
else:
print("Incorrect")
print("The Answer was 1035")
And:
def Math():
MathA()
return
Related
I'm writing a simple unit converter where the user can pick which units they want to convert from two options. I'm using radio-buttons for the choice, but can't seem to get the value of the chosen one to work in the conditions at the bottom of the program.
I tried several solutions suggested here on stack overflow, but none of them worked. At one point, I got the selected() to print the value of the button, but it still didn't work in the condition. Am I missing something obvious here?
Please, note, the converter is not finished yet, there is still some more polishing to do after this issue is solved.
from tkinter import *
window = Tk()
window.title("Unit converter")
window.minsize(width=300, height=300)
window.config(padx=50, pady=50)
def lbs_kgs():
user_input = float(unit_A1.get())
result = round((user_input / 2.2046), 2)
unit_B1.config(text= f"{result}")
def mil_km():
user_input = float(unit_A1.get())
result = round((user_input * 1.6), 2)
unit_B1.config(text= result)
def selected():
return radio_state.get()
intro_label = Label(text = "What units would you like to convert?")
intro_label.grid(column=0, row=0, columnspan=4, pady=10)
radio_state = StringVar()
radiobutton1 = Radiobutton(text="Pounds to kilograms", value="pk", variable=radio_state, command=selected)
radiobutton2 = Radiobutton(text="Miles to kilometers", value="mk", variable=radio_state, command=selected)
radiobutton1.grid(column=0, row=1, columnspan=4)
radiobutton2.grid(column=0, row=2, columnspan=4)
instructions_label = Label(text = "Enter the number:")
instructions_label.grid(column=0, row=3, columnspan=4, pady=10)
unit_A1 = Entry(width=5)
unit_A1.grid(column=1, row=4, sticky="e")
unit_A1_label = Label(text = "unit A1")
unit_A1_label.grid(column=2, row=4, sticky="w")
equal_label = Label(text = "is equal to")
equal_label.grid(column=1, row=5, sticky="e")
unit_B1 = Label(text = "0")
unit_B1.grid(column=2, row=5, sticky="w")
unit_B1_label = Label(text = "result unit")
unit_B1_label.grid(column=3, row=5, sticky="w")
button = Button(text="Calculate")
button.grid(column=0, row=6, columnspan=4, pady=10)
if selected() == "pk":
button.config(command=lbs_kgs)
elif selected() == "mk":
button.config(command=mil_km)
window.mainloop()
Move the if/else check into the selected function so the conditions can be checked each time the selection changes
def selected():
selection = radio_state.get()
if selection == "pk":
button.config(command=lbs_kgs)
elif selection == "mk":
button.config(command=mil_km)
In line 29 should be radio_state = StringVar(window, '1'). Without this when executed both radiobutton are on, but that not right.
def selected():
if (selection := radio_state.get()) == "pk":
button.config(command=lbs_kgs)
elif selection == "mk":
button.config(command=mil_km)
Output:
Output pound to Kilograms:
Output Miles to Kilometers:
I've been having some troubles with this code as the if condition cannot be true and always executes the else condition instead.
can you help
`
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = entry_1.get().strip()
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()
Thanks
Any user input is a string, so you need to convert to an Integer.
Try this code:
from tkinter import *
root = Tk()
entry_1 =Entry(root, width = 20)
entry_1.pack()
entry_1.insert(0, "Choose Your Number ")
def m():
answer = int(entry_1.get().strip())
if answer == 5 :
mylabel = Label(root, text = "YOU WIN!")
mylabel.pack()
else :
mylabel = Label(root, text = "YOU LOST!")
mylabel.pack()
mybutton = Button(root, text = 'PLAY', command = m)
mybutton.pack()
root.mainloop()
here is my code:
from tkinter import *
import random
def initGame():
window = Tk()
window.title("Guess the number game")
lbl = Label(window, text="Guess number from 1 to 100. Insert how many tries would you like to have: ", font=("",16))
lbl.grid(column=0, row=0)
txt = Entry(window, width=10)
txt.grid(column=0, row=1)
txt.focus() #place cursor auto
def clicked():
number_dirty = txt.get()
tries = int(number_dirty)
playGame(tries)
btn = Button(window, text="Start", command=clicked)
btn.grid(column=0, row=2)
window.geometry('800x600')
window.mainloop()
def playGame(tries):
number_of_tries = int(tries)
number = random.randint(1,100)
higher_notification = "Number is HIGHER"
lower_notification = "Number is LOWER"
game_window = Tk()
game_window.title("Game Window")
lbl = Label(game_window, text="Guess numbers between 1 and 100, you have %s tries !" %(number_of_tries), font=("",14))
lbl.grid(column=0, row=0)
txt = Entry(game_window, width=10)
txt.grid(column=0, row=1)
txt.focus()
print(number)
print(number_of_tries)
def clicked():
user_input = txt.get()
compareNumbers(number, user_input)
btn_try = Button(game_window, text="Try!", command="clicked")
btn_try.grid(column=0, row=2)
def compareNumbers(number, user_input):
if user_input == number:
messagebox.showinfo('You have won!', 'Right! the number was %s ' %(number))
else:
if user_input > number:
lbl.configure(lower_notification)
number_of_tries -1
else:
lbl.configure(higher_notification)
number_of_tries -1
game_window.geometry('600x600')
game_window.mainloop()
initGame()
On the first screen (initGame) everything works fine, when I click the button I do indeed get the second screen, which displays all objects normally. When I click the button in the game screen I get no feedback at all, nothing happens.
What am I missing?
Thank you very much !
The problem is in this line:
btn_try = Button(game_window, text="Try!", command="clicked")
Note that the command "clicked" is inside quotaions marks and therefor a string and not the method you tried to reference. What you want is:
btn_try = Button(game_window, text="Try!", command=clicked)
Can someone help me, Im trying to make a banking program and when i try to login and enter the correct details, it still says "notok". I put in some values for testing purposes and it just wont work and it would always print notok. Please help
import tkinter as tk
from tkinter import messagebox
import random
def checklog(ac,pin):
if (ac==1) and (pin==2):
print("ok")
else:
print("notok")
def exitwin(master):
master.destroy()
def acc_no(master):
acc_no.acc = random.randrange(1000000000,9999999999)
messagebox.showinfo("Account Number", acc_no.acc)
return
def openac():
op = tk.Tk()
op.title("Open a account")
op.minsize(500,500)
op.configure(bg='gray90')
l1 = tk.Label(op, text="Full Name")
l1.grid(row=0, column=2)
openac.name = tk.Entry(op)
openac.name.grid(row=0, column=3)
l2 = tk.Label(op, text="Enter Starting Deposit")
l2.grid(row=1, column=2)
openac.fun = tk.Entry(op)
openac.fun.grid(row=1, column=3)
l3 = tk.Label(op, text="Enter your pin")
l3.grid(row=2, column=2)
openac.pin = tk.Entry(op, show="*")
openac.pin.grid(row=2, column=3)
sub = tk.Button(op, text="Submit", command=lambda: [acc_no(op), login(), exitwin(op)])
sub.grid(row=3, column=1)
op.bind("<Return>", lambda x:[dep(op, e1.get(),e2.get(), e3.get()), acc_no(op), login(op, e1.get(), e2.get(), e3.get()), exitwin(op)])
return
def login():
log = tk.Tk()
log.title("Login")
log.minsize(500,500)
l1 = tk.Label(log, text="Enter your account number")
l1.grid(row=0, column=0)
e1 = tk.Entry(log)
e1.grid(row=0, column=1)
l2 = tk.Label(log, text="Enter your pin")
l2.grid(row=1, column=0)
e2 = tk.Entry(log)
e2.grid(row=1, column=1)
sub = tk.Button(log, text="Sumbit", command=lambda: checklog(e1.get(), e2.get()))
sub.grid(row=1, column=2)
return
log.mainloop()
def dep(master, name, fund, pin):
x=0
def draw():
x=0
def mainmenu():
mm = tk.Tk()
mm.title("Bank")
mm.minsize(400,400)
mm.configure(bg='gray70')
l1 = tk.Label(mm, text="HELLO")
l1.config(font=("Courier", "25"))
l1.grid(row=0)
b1 = tk.Button(mm, text="Sign Up", command=openac)
b1.grid(row=2)
b2 = tk.Button(mm, text="Log In", command=lambda: login(mm))
b2.grid(row=3)
mm.mainloop()
mainmenu()
You're checking if the .get()'s of your text boxes are equal to an integer, but you have not converted them into an integer, they are a string by default.
def checklog(ac, pin):
if ac == "1" and pin == "2":
print("ok")
else:
print("not ok")
Best practice dictates that you convert the value to an integer yourself and throw an error when it cannot be converted. Something that tells the user their account number or pin failed validation as it is not a number.
The values that you pass to checklog come from calling .get on a tk.Entry, which produces a string (it must do this, because you could type whatever text you like, not just ones that look like numbers). The comparison ac==1 fails because ac is a string. You must convert the value yourself, and handle the case when a non-number is typed.
This is not really a Tkinter question; it's the same problem that beginners have all the time with input().
I got some trouble with finding the matching if-statement to check if only one entry equals 0 of 3.
Here's the code:
def thanx(self):
if len(self.e.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
It is only checking if my variable e equals 0, but i actually got 2 more entries. I know i could check every single one individually, however there has to be an easier way of doing this.
Im using "tkinter" btw, but this shouldnt be too much important.
I tried it with or but this isn't working or I'm doing it wrong.
(Also tried to solve this with lambda, but again just errors...)
Maybe someone can help me there...
Edit:
I might have explained this a bit confusing, I'll add the rest of the code here that you can understand this better:
from tkinter import Tk, Label, Entry, Button, W
from tkinter import messagebox
class MyForm:
def thanx(self):
if len(self.e.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
def callback(self):
#print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
if self.boo:
f = open("PrivatData.txt", "w+")
f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
def __init__(self):
self.root = Tk()
self.root.title("Your privat details")
Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5)
Label(self.root, text="Password").grid(row=1, padx=12, pady=5)
Label(self.root, text="Email").grid(row=2, padx=12, pady=5)
self.e = Entry(self.root)
self.e2 = Entry(self.root)
self.e3= Entry(self.root)
self.e.grid(row=0,column=1,columnspan=2)
self.e2.grid(row=1, column=1, columnspan=2)
self.e3.grid(row=2, column=1, columnspan=2)
self.e.focus_set()
self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()])
self.quit = Button(self.root,text="Quit", command = self.root.quit)
self.show.grid(row=3, column=1, pady=4)
self.quit.grid(row=3, column=2, sticky = W, pady=4)
self.root.geometry("230x140")
self.root.configure(background= "#65499c")
self.root.mainloop()
if __name__ == "__main__":
app= MyForm()
Use any:
if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)):
do stuff to say that user did not input all fields
else:
do stuff to say that user inputted all fields
So full code:
from tkinter import Tk, Label, Entry, Button, W
from tkinter import messagebox
class MyForm:
def thanx(self):
if any((len(self.e.get().strip())==0,len(self.e2.get().strip())==0,len(self.e2.get().strip())==0)):
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
def callback(self):
#print("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
if self.boo:
f = open("PrivatData.txt", "w+")
f.write("Name: %s\nPassword: %s\nEmail: %s" % (self.e.get(), self.e2.get(),self.e3.get()))
def __init__(self):
self.root = Tk()
self.root.title("Your privat details")
Label(self.root, text="Your Name").grid(row = 0, padx = 12, pady=5)
Label(self.root, text="Password").grid(row=1, padx=12, pady=5)
Label(self.root, text="Email").grid(row=2, padx=12, pady=5)
self.e = Entry(self.root)
self.e2 = Entry(self.root)
self.e3= Entry(self.root)
self.e.grid(row=0,column=1,columnspan=2)
self.e2.grid(row=1, column=1, columnspan=2)
self.e3.grid(row=2, column=1, columnspan=2)
self.e.focus_set()
self.show= Button(self.root, text="Submit", command=lambda:[self.thanx(),self.callback()])
self.quit = Button(self.root,text="Quit", command = self.root.quit)
self.show.grid(row=3, column=1, pady=4)
self.quit.grid(row=3, column=2, sticky = W, pady=4)
self.root.geometry("230x140")
self.root.configure(background= "#65499c")
self.root.mainloop()
if __name__ == "__main__":
app= MyForm()
I am assuming that at the moment you are checking if some string element equals 0.
For example
e = 'abc'
len(e) == 3 # True
l = []
len(l) == 0 # True
If you want to check if your string variable is 0 then simply:
if not self.e.get():
messagebox.showerror("Error")
self.boo = False
You may try this:
if len(self.e.get()) == 0 or len(self.e2.get()) == 0 or len(self.e3.get()) == 0:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
Since you have 3 variables, there's no way to check them all 'in batch' unless you build a data structure containing them and then check some conditions on that data structure. However, it does not give any advantage. If you add a new variable, say e4, you still have to add it manually to the the data structure.
To ensure that all three textboxes are not empty in one if statement, you can use the following:
if "" in [self.e.get().strip(), self.e2.get().strip(), self.e3.get().strip()]:
messagebox.showerror("Error", "Please enter affordable infos")
self.boo = False
else:
messagebox.showinfo("Submition done", "Thank you")
self.boo = True
This is a short and neat way to write what you are trying to do. This works because entry widgets will return "" if they are empty, and self.e.get().strip() makes the text returned empty (.strip() removes all whitespace at both the start and the end of the string) if it is just whitespace (" ", \t, n, etc...).
It is better to check the contents of the string rather than the length of it, because a box with just whitespace in it will not return 0, as shown below.
>>> len(" ")
1
>>> len("")
0
>>> len("\t")
1