Python Tkinter project - python

I'm working on a final for python. My goal is to make a code that uses Tkinter to ask the user to input the answer to a math problem using an entry box then press submit. I want to be able to have python do something depending on whether the answer is right or wrong, but I'm not sure how to do this with Tkinter. How do I make it "check" the answer? For example,
ent = Entry(pyfinal)
btn = Button(pyfinal, text="Submit", bg="#000000")
lbl = Label(pyfinal, text="What is the answer to 5 x 5?")
If I was using regular python, I would do this,
ent = int(input('What is 5 x 5? '))
if ent == int ('25'):
print ("correct")
else:
print ("wrong, try again.")
How would I do that with Tkinter while keeping it all in the Tkinter window?
Thanks

Try using if statements for example:
Mp = Answer to math problem
Answer = What user wrote
If Mp == Answer:
Lbl = Label("You are right")
Lbl2.pack()
Lbl.after(3000, lambda: label.destroy())
Else:
Lbl2 = Label("You are wrong')
Lbl2.pack()
Lbl2.after(3000, lambda: label2.destroy())
Only write the .after statement if you want to delete this label in a certain amount of time

Related

How to run a function from a button based GUI window?

I'm trying to make a menu driven program that has GUI capability. For the sake of this post I edited it down so the menu has 2 options, to quit and to calculate an average of a set of numbers. I ran this before I used the GUI code and it worked perfectly.
The issue is that when I click "Average", it runs the function and allows 1 input but then I can't enter another number. Same issue with other functions I had. They won't run past the first input and then the Quit button also won't quit.
Feel free to ask any questions in the comments if I wasn't good at describing what I needed. It's my first day using GUI so sorry if anything looks weird, I'm trying to teach myself but got stuck here. End goal is to have the whole program run in a GUI environment but I figured starting with the menu would be the best place to start.
from tkinter import *
import tkinter as tk
def average():
print("Enter test scores to get the average of. Type '-99' to quit.")
num = 1
count = 0
total = 0
while num != -99:
num = int(input("Enter numbers: "))
total += num
count += 1
average = (total + 99) / (count-1)
print("The average is: ", average)
print("-----------")
main()
def main():
r = tk.Tk()
r.title('Number games')
button1 = tk.Button(r, activebackground = "blue", bg = "light blue", text='Average', width=25, command= average)
button4 = tk.Button(r, activebackground = "blue", bg = "light blue", text='Quit', width=25, command=r.destroy)
button1.pack()
button4.pack()
r.mainloop()
main()
You don't need to call main() from inside average(). When I delete that line, your program works exactly as expected for me (debian 9, python3).
Ps. Don't use import *.
Globalize the variable r and declare r.destroy() in another function above main function. Note from tkinter import * is enough no need to import tkinter again with an alias.

Is it possible to display python input statements in Tkinter?

I've python code that takes user input, hence I'm using lots of input statements. Now I'm creating GUI using Tkinter and want to display those input statements in Tkinter. Is there a way to to it?
For ex.
var=float(input("enter a number"))
Now I want to show the input statement "enter a number in Tkinter". Is it possible to do it? If yes, how?
Rather than using the input function, you could user tkinter's askstring command. This will bring up a small dialog box with the question asked and return the user's entry to the script.
import tkinter as tk
import tkinter.simpledialog as sd
def getUserInput():
userInput = sd.askstring('User Input','Enter your name')
print(f'You said {userInput}')
root = tk.Tk()
btn = tk.Button(root,text="Get Input", command=getUserInput)
btn.grid()
root.mainloop()
If you wish to ask for numerical values, tkinter also has askfloat and askinteger functions. These allow you to specify minimum and maximum values.
import tkinter as tk
import tkinter.simpledialog as sd
def getUserInput():
userInput = sd.askstring('User Input','Enter your name')
print(f'You said {userInput}')
def getUserFloatInput():
options = {'minvalue':3.0,'maxvalue':4.0}
userInput = sd.askfloat('User Input','Enter an approximation of Pi',**options)
print(f'You said pi is {userInput}')
def getUserIntegerInput():
options = {'minvalue':4,'maxvalue':120}
userInput = sd.askinteger('User Input','How old are you?',**options)
print(f'You said you are {userInput}')
root = tk.Tk()
btn1 = tk.Button(root,text="Get String Input", command=getUserInput)
btn1.grid()
btn2 = tk.Button(root,text="Get Float Input", command=getUserFloatInput)
btn2.grid()
btn3 = tk.Button(root,text="Get Integer Input", command=getUserIntegerInput)
btn3.grid()
root.mainloop()

Python,Tkinter, making a username/password interface

Beginner to python. Can't seem to figure out how to set a password to these
entries.Looked into a bunch of sites already. Any examples or feedback is much appreciated.Thanks...............................................
from tkinter import*
from PIL import Image,ImageTk
import glob,os
root=Tk()
w1=Label(root,text="1")
w2=Label(root,text="2")
w3=Label(root,text="3")
e1=Entry(text="five")
e2=Entry(text="six")
e3=Entry(text="seven")
text=(e1)
def show_entry_fields():
print("1:%s\n2:%s\n3:%s" %(e1.get(),e2.get(),e3.get()))
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
b1=Button(root,text="Submit",command=show_entry_fields).grid(row=3,column=3)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e3.grid(row=2,column=1)
w1.grid(row=0)
w2.grid(row=1)
w3.grid(row=2)
image=Image.open("beer.png")
photo=ImageTk.PhotoImage(image)
label=Label(image=photo)
label.image=photo#keep a reference
label.grid(column=4)
mainloop()
Can't seem to figure out how to set a password to these entries.
Going from your comment:
rather set a password to each entry.
This might be more along the lines of what you are attempting to do.
The below code will check if each entry field has the correct password.
if so it prints success and if not it prints try again.
from tkinter import *
root=Tk()
Label(root, text="1").grid(row=0)
Label(root, text="2").grid(row=1)
Label(root, text="3").grid(row=2)
e1=Entry(root)
e2=Entry(root)
e3=Entry(root)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e3.grid(row=2,column=1)
def test_entry_fields():
if e1.get() == "five" and e2.get() == "six" and e3.get() == "seven":
print("You have entered the correct passwords!")
else:
print("Please try again.")
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
b1=Button(root,text="Submit",command=test_entry_fields).grid(row=3,column=3)
mainloop()
If you are trying to create a "mask" to cover the input of a password field, for example "Hunter2" becomes "*******" then use this.
show="*"
-> replacing * with whichever char you want to use as a mask.
for example, to use the second textbox you have as a password field.
e2=Entry(text="six", show="*")

Why does this not work? (Python)

(Python 3.4.1)
Hey, I have this simple little guess my number game in Tkinter but it doesn't work for some reason... Can anyone see why?
from tkinter import *
from random import random
import tkinter.messagebox
window = Tk()
def Guess():
if int(guessnum) == int(Number):
print("Well Done!")
exit()
elif int(guessnum) >= int(Number):
print("Too big")
elif int(guessnum) <= int(Number):
print("Too small")
Number = (round(random() * 10))
window.title("Guess My Number")
window["padx"] = 70
window["pady"] = 20
guessnum="1"
entryWidget=Entry(window,textvariable=guessnum).grid(row=1,column=0)
button = Button(window, text="Guess",command=Guess()).grid(row=2,column=0)
window.mainloop()
You have made two classic Tkinter errors in one line:
button = Button(window, text="Guess", command=Guess()).grid(row=2,column=0)
# ^ assigned result of call to command, not
# the actual function
# ^ assigned result of grid
# (None) to button rather
# than the Button
This line is equivalent to something like:
Guess()
_ = Button(..., command=None)
button = _.grid(...)
You should have done:
button = Button(window, text="Guess", command=Guess)
button.grid(row=2,column=0)
Note parentheses removed from Guess and grid call split out to separate line
The testvariable option must be an instance of the StringVar class.
guessnum = StringVar
guessnum.set("1") # optional, otherwise '' I believe
I recommend this tkinter reference and use it constantly when programming tkinter widgets I am not completely familiar with, and even sometimes when answering questions here.

In python, using tkinter, my random numbers only generate once?

Basically, I have this code:
from tkinter import *
from tkinter import messagebox
import random
import string
from tkinter import filedialog
ktwoWin = Tk() #window
qLabel = StringVar()
userAnswer = StringVar()
ktwoWin.withdraw() #hide the ktwoWin window
pass
num1= random.randint(1, 12) #random numbers
num2= random.randint(1, 12)
Answer= num1 * num2
def ktwoOpen():
ktwoWin.deiconify() #show the ktwoWin window
ktwoWin.title("Kindergarten to Grade Two")
ktwoWin.geometry("400x300")
ktwoWin.grid()
askbutton= Button(ktwoWin, text="ask me a question!", command = askquestion, height=3, width=16, bg="blue")
askbutton.grid(column= 0, row= 0)
submitbtn= Button(ktwoWin, text="Submit Answer", command=checkanswer, height=3, width=12, bg= "red")
submitbtn.grid(column=1, row=0)
q=Label(ktwoWin,textvariable=qLabel)
q.grid(column=1, row=1)
q.config(text="text to go here")
qLabel.set("some text")
answerentry= Entry(ktwoWin, textvariable=userAnswer)
answerentry.grid(column=3, row=3)
pass
def askquestion():
qLabel.set("what is" +str(num1) + "x" + str(num2) + "?")
def checkanswer():
useranswer=userAnswer.get()
if int(useranswer) != Answer:
messagebox.showwarning(message="the answer is " + str(Answer))
else:
messagebox.showinfo(message="correct!")
ktwoWin.mainloop
Which, when I run the program, the random numbers I have, will only randomise once, if that makes sense? My question, ultimately, is there a way for me to loop the random number part of the code?
any help is appreciated, thanks:)
It should be pretty straight forward to set up a new question each time one is answered. I'm not an expert at tkinter, so this is fairly general advice.
To start with, set up your two random numbers in the askquestion function, rather than at the top level of your module. Since you need to be able to access the product later, use the global keyword to make sure that the answer is available outside the function's scope (or you could reorganize the code into a class and use member variables).
You may also need to add some extra logic to the end of the checkanswer function to reset the program's state after an answer has been provided (e.g. clear the old question label and remove the old answer from the input box). Depending on how you want the program to play, you might immediately ask a new question, or you might go back to the original starting state.

Categories