(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.
Related
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.
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()
My tkinter window not opened after i add while true function. How can I get this to work. Its works without while true, but i need it in my function.
from tkinter import *
from random import random
import sys
import random
maxcount = int (input("How many times "))
i = 1
cats = Tk()
cats.wm_title("maxcount test")
cats.geometry("500x500")
def black():
while True:
i+1
if i == 5:
break
Button(cats, text="Start", command=black()).grid(row=1, column=0)
Label(cats, text="How many times:").grid(row=0, column=0)
cats.mainloop()
You had two errors:
- i + 1 probably meant i += 1, then i musty be declared global so it can be modicied in the scope of the function.
- the Button command was black(), which is a call to the function black. What is needed is a reference to the function black (without the ())
One thing to note: as remarked by #Sierra_Mountain_Tech, as it is, the user must first input an integer for the
tkinter app to start.
from tkinter import *
from random import random
import sys
import random
maxcount = int (input("How many times "))
i = 1
cats = Tk()
cats.wm_title("maxcount test")
cats.geometry("500x500")
def black():
global i
while True:
i += 1
if i >= 5: # <-- changed from i == 5 at #Sierra_Mountain_Tech suggestion
break
Button(cats, text="Start", command=black).grid(row=1, column=0)
Label(cats, text="How many times:").grid(row=0, column=0)
cats.mainloop()
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
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.