How to get data from a command run in a button - python

I fixed the previous problem I had with the function, but now I'm not sure how to get the changed variables from the function to change the label.
from tkinter import *
import tkinter.messagebox
import random
def testTrue(firstNo,secondNo):
if firstNo + secondNo == int(entry1.get()):
firstNo = random.randint(1,15)
secondNo = random.randint(1,15)
problem = ("What is",firstNo,"+",secondNo)
tkinter.messagebox.showinfo("Answer", "Correct")
elif firstNo + secondNo != entry1.get():
tkinter.messagebox.showinfo("Answer", "Wrong, try again!")
main = Tk()
entryType = IntVar()
firstNo = random.randint(1,15)
secondNo = random.randint(1,15)
problem = ("What is",firstNo,"+",secondNo)
label1 = Label(main,text=problem).grid(row=0, sticky=E)
entry1 = Entry(main,textvariable=entryType)
entry1.grid(row=0,column=1)
submitButton = Button(main,text="Submit",command=lambda: testTrue(firstNo,secondNo)).grid(columnspan=2,row=2)
main.mainloop()

Related

My Python Label text doesn't change though I am using a StringVar for the same .What's to be changed?

import random
import tkinter as tk
from tkinter import *
def roll():
lbl_result["text"] = str(random.randint(1, 6))
window = tk.Tk()
v = tk.StringVar()
v.set("Result")
window.columnconfigure([0,2], minsize=150)
window.rowconfigure([0, 2], minsize=50)
btn_roll = tk.Button(bg ="YELLOW",fg = "BLUE",text="Roll", command=roll)
btn_roll.grid(row =0,column =1)
lbl_result = tk.Label(width = 2,height =1,bg="GREEN",fg="YELLOW")
btn_roll.grid(row=0, column=1, sticky="nsew")
lbl_result.grid(row=2, column=1)
a = lbl_result.cget('text')
print(" Random no is :",a)
if a == "6":
v.set("You Win")
lbl_result1 = tk.Label(textvariable = v,width = 6,height=2,bg="BLUE",fg="YELLOW")
lbl_result1.grid (row=1,column=1)
window.mainloop()
I incorporated the Label text change that I wanted inside the function that's called by the command button. Now the code works fine.
Earlier the function called was like this
def roll():
lbl_result["text"] = str(random.randint(1, 6))
NOW I changed it to
def roll():
lbl_result["text"] = str(random.randint(1, 6))
if lbl_result["text"] == "6":
lbl_result1["text"] = " U Win"

Get input in Python tkinter Entry when Button pressed

I am trying to make a 'guess the number' game with Pyhon tkinter but so far I have not been able to retrieve the input from the user.
How can I get the input in entry when b1 is pressed?
I also want to display a lower or higher message as a clue to the player but I am not sure if what I have is right:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
guess = 0
def get(entry):
guess = entry.get()
return guess
def main():
b1 = tk.Button(root, text="Guess", command=get)
entry = tk.Entry()
b1.grid(column=1, row=0)
entry.grid(column=0, row=0)
root.mainloop()
print(guess)
if guess < randomnum:
l2 = tk.Label(root, text="Higher!")
l2.grid(column=0, row=2)
elif guess > randomnum:
l3 = tk.Label(root, text="Lower!")
l3.grid(column=0, row=2)
while guess != randomnum:
main()
l4 = tk.Label(root, text="Well guessed")
time.sleep(10)
You could define get inside main, so that you can access the entry widget you created beforehand, like this:
entry = tk.Entry()
def get():
guess = entry.get()
return guess # Replace this with the actual processing.
b1 = tk.Button(root, text="Guess", command=get)
You've assembled random lines of code out of order. For example, the root.mainloop() should only be called once after setting up the code but you're calling it in the middle of main() such that anything after won't execute until Tk is torn down. And the while guess != randomnum: loop has no place in event-driven code. And this, whatever it is, really should be preceded by a comment:
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
Let's take a simpler, cleaner approach. Rather than holding onto pointers to the the various widgets, let's use their textvariable and command properties to run the show and ignore the widgets once setup. We'll use StringVar and IntVar to handle input and output. And instead of using sleep() which throws off our events, we'll use the after() feature:
import tkinter as tk
from random import randint
def get():
number = guess.get()
if number < random_number:
hint.set("Higher!")
root.after(1000, clear_hint)
elif number > random_number:
hint.set("Lower!")
root.after(1000, clear_hint)
else:
hint.set("Well guessed!")
root.after(5000, setup)
def setup():
global random_number
random_number = randint(1, 100)
guess.set(0)
hint.set("Start Guessing!")
root.after(2000, clear_hint)
def clear_hint():
hint.set("")
root = tk.Tk()
hint = tk.StringVar()
guess = tk.IntVar()
random_number = 0
tk.Entry(textvariable=guess).grid(column=0, row=0)
tk.Button(root, text="Guess", command=get).grid(column=1, row=0)
tk.Label(root, textvariable=hint).grid(column=0, row=1)
setup()
root.mainloop()
Here is a tkinter version on the number guessing game.
while or after are not used!
Program checks for illegal input (empty str or words) and reports error message. It also keeps track of the number of tries required to guess the number and reports success with a big red banner.
I've given more meaningful names to widgets and used pack manager instead of grid.
You can use the button to enter your guess or simply press Return key.
import time
import random
import tkinter as tk
root = tk.Tk()
root.title( "The Number Guessing Game" )
count = guess = 0
label = tk.Label(root, text = "The Number Guessing Game", font = "Helvetica 20 italic")
label.pack(fill = tk.BOTH, expand = True)
def pick_number():
global randomnum
label.config( text = "I am tkinking of a Number", fg = "black" )
randomnum = random.choice( range( 10000 ) )/100
entry.focus_force()
def main_game(guess):
global count
count = count + 1
entry.delete("0", "end")
if guess < randomnum:
label[ "text" ] = "Higher!"
elif guess > randomnum:
label[ "text" ] = "Lower!"
else:
label.config( text = f"CORRECT! You got it in {count} tries", fg = "red" )
root.update()
time.sleep( 4 )
pick_number()
count = 0
def get( ev = None ):
guess = entry.get()
if len( guess ) > 0 and guess.lower() == guess.upper():
guess = float( guess )
main_game( guess )
else:
label[ "text" ] = "MUST be A NUMBER"
entry.delete("0", "end")
entry = tk.Entry(root, font = "Helvetica 15 normal")
entry.pack(fill = tk.BOTH, expand = True)
entry.bind("<Return>", get)
b1 = tk.Button(root, text = "Guess", command = get)
b1.pack(fill = tk.BOTH, expand = True)
pick_number()
root.geometry( "470x110" )
root.minsize( 470, 110 )
root.mainloop()
Correct way to write guess number.
I write a small script for number guessing game in Python in
get_number() function.
Used one widget to update Label instead of duplicating.
I added some extra for number of turns that you entered.
Code modified:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
print(randomnum)
WIN = False
GUESS = 0
TURNS = 0
Vars = tk.StringVar(root)
def get_number():
global TURNS
while WIN == False:
Your_guess = entry.get()
if randomnum == float(Your_guess):
guess_message = f"You won!"
l3.configure(text=guess_message)
number_of_turns = f"Number of turns you have used: {TURNS}"
l4.configure(text=number_of_turns)
l4.grid(column=0, row=3, columnspan=3, pady=5)
WIN == True
break
else:
if randomnum > float(Your_guess):
guess_message = f"Your Guess was low, Please enter a higher number"
else:
guess_message = f"your guess was high, please enter a lower number"
l3.configure(text=guess_message)
l3.grid(column=0, row=2, columnspan=3, pady=5)
TURNS +=1
return Your_guess
label = tk.Label(root, text="The Number Guessing Game", font="Helvetica 12 italic")
label.grid(column=0, row=0, columnspan=3, sticky='we')
l2 = tk.Label(root, text='Enter a number between 1 and 100',
fg='white', bg='blue')
l2.grid(row=1, column=0, sticky='we')
entry = tk.Entry(root, width=10, textvariable=Vars)
entry.grid(column=1, row=1, padx=5,sticky='w')
b1 = tk.Button(root, text="Guess", command=get_number)
b1.grid(column=1, row=1, sticky='e', padx=75)
l3 = tk.Label(root, width=40, fg='white', bg='red' )
l4 = tk.Label(root, width=40, fg='white', bg='black' )
root.mainloop()
while guess:
time.sleep(10)
Output for enter floating numbers:
Output after the guess was high:
Output after the guess was low:
Output You won and number of turns:

Python 3.4 tkinter real-time temperature converter

I wrote complicated program in Python 3.4 (with tkinter gui). It's temperature converter (Celsius to Fahrenheit and reverse) in real-time. It works almost good, but there is one problem. I have to add a space after input value every time. Anyone have idea what's wrong in this program?
from tkinter import *
def cel_na_fahr(event):
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a+event.char)
else:
ent2.delete(0,END)
ent2.insert(0,a+event.char)
def fahr_na_cel(event):
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a+event.char)
else:
ent1.delete(0,END)
ent1.insert(0,a+event.char)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<Key>', cel_na_fahr)
ent2.bind('<Key>', fahr_na_cel)
root.mainloop()
You have to type a space because when the <Key> callback triggers, the key that the user most recently pressed hasn't yet been added to the entry. This is probably what you're trying to compensate for by adding event.char, although you're doing it in the wrong place anyway.
Change your bindings to KeyRelease, so that the callbacks trigger after the entry is updated, and remove the +event.char stuff, as you don't need it any more.
from tkinter import *
def cel_na_fahr(event):
print(ent1.get())
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a)
else:
ent2.delete(0,END)
ent2.insert(0,a)
def fahr_na_cel(event):
print(ent2.get())
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a)
else:
ent1.delete(0,END)
ent1.insert(0,a)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<KeyRelease>', cel_na_fahr)
ent2.bind('<KeyRelease>', fahr_na_cel)
root.mainloop()

Python, Tkinter a mathgame how to make a point-system

I'm on a simple project to make a math game. So far everything good, the user can choose to multiply or add. Then recives a multiplication to solve or a addition, then is give feedback. But I wish to extend my game, I want to make some kind of count/Highscore but not complicated only to give the user feedback in the simplest way, like if they get 5 answers correct in a row it will say in a text-box "Congratulations you've got 5 points". I'm not sure how to go further on with this project, simply I want it to be a python math-game made in Tkinter with a count function for each correct answer.
I'm using Tkinter & Python 2.7 for this, further on I wish to make a tutorial on this project to post on youtube. And all help is very very appreciated.
from Tkinter import *
import tkMessageBox
import random
import time
def fraga():
global num1
num1 = random.randint(1, 100)
global num2
num2 = random.randint(1, 100)
global svar
svar = num1 + num2
label1.config(text='Vad blir ' + str(num1) + '+' + str(num2) + '?')
entry1.focus_set()
def fraga1():
global num3
num3 = random.randint(1, 10)
global num4
num4 = random.randint(1, 10)
global svar1
svar1 = num3 * num4
label1.config(text='Vad blir ' + str(num3) + '*' + str(num4) + '?')
entry1.focus_set()
def svar1():
mainAnswer = entry1.get()
# feedback på tom ruta
if len(mainAnswer) == 0:
tkMessageBox.showwarning(message='Skriv in några nummer!')
return
if int(mainAnswer) != svar1:
tkMessageBox.showwarning(message='Tyvärr det rätta svaret: ' + str(svar1))
else:
tkMessageBox.showinfo(message='RÄTT!! :)')
def svar():
mainAnswer = entry1.get()
# feedback på tom ruta
if len(mainAnswer) == 0:
tkMessageBox.showwarning(message='Skriv in några nummer!')
return
if int(mainAnswer) != svar:
tkMessageBox.showwarning(message='Tyvärr det rätta svaret: ' + str(svar))
else:
tkMessageBox.showinfo(message='RÄTT!! :)')
def quit():
global root
root.destroy()
#fönster
root = Tk()
root.title("Andrejs mattespel Quiz")
root.geometry('700x700')
# välkomstmeddelande
label2 = Label(root, text="Hej!\n Nu ska vi lösa lite matteproblem!")
label2.config(font=('times', 18, 'bold'), fg='black', bg='white')
label2.grid(row=0, column=0)
#labels
label1 = Label(root)
label1.grid(row=2, column=0)
#start
entry1 = Entry(root)
entry1.grid(row=3, column=0)
# Omstartknappen
entry1.bind('<Return>', func=lambda e:checkAnswer())
#Knappar
fragaBtn = Button(root, text='Jag vill öva på addition!', command=fraga)
fragaBtn.grid(row=4, column=0)
svarButton = Button(root, text='Svar addition', command=svar)
svarButton.grid(row=4, column=1)
quit_bttn = Button(root, text = "Avsluta", command=quit)
quit_bttn.grid(row = 4, column = 3, sticky = W)
#Knappar multiplikation
Make a score variable and increment by 1 each time the user is right.
Now make a list named highscores. This should give you the idea of what to do:
#when user looses
if score > highscores[-1]:
highscores[-1] = score
highscores.sort()
#Then display a list of best results with the current result marked or something :)
If you want to save scores, you need to write them to a file. The easiest ways to do so would be the json module. Just json.dump(highscores, open(path, 'w')) to save and highscores = json.load(open(path)) to reload from the file would do when dealing with lists and dicts.

Tkinter Math Quiz

What is wrong with this program? Every time I run it the first math problem is show before I push start. Also the answer is always the first math problem, it never changes. Also there should not be a math problem above the timer. Thanks, Scott
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
answer = Questions()
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
Your problem is with how you're calling the Questions() method. You only ask for the answer once with
answer = Questions()
and you do this before you press start (which is why it shows up before you hit start)
To fix it you could use code like this:
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
global answer
answer = Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
In this code the answer is updated every time you hit start and only updates when you hit start.

Categories

Resources