Tkinter Display Label does not udpate - python

The displayed score on the Tkinter window does not update on each loop. But if you check in the terminal score is been updated
Tk Window does not update
The terminal score has been updated
score = 0
def check():
global score
if answered_question[1]['correct_answer'] == 'True':
score += 1
root = tk.Tk()
root.config(padx=20, pady=20, bg=BLUE_GRAY)
score_board = tk.Label(
text=f"Score: {score}",
bg=BLUE_GRAY, fg="white",
font=('Arial', 10, "normal")
)
check_btn = tk.Button(image=check_img, command=check, highlightthickness=0)
root.mainloop()

You have to update the label explicitly by using either config/configure (same thing), or by binding a tk.StringVar() to your Label's textvariable parameter
# Option One
def check():
global score
if answered_question[1]['correct_answer'] == 'True':
score += 1
# update the label
score_board.configure(text=f'Score: {score}')
or...
# Option Two
def check():
global score
if answered_question[1]['correct_answer'] == 'True':
score += 1
# update the label
label_var.set(f'Score: {score}')
... # code omitted for brevity
label_var = tk.StringVar() # declare a tk.StringVar to bind to your label
score_board = tk.Label(
text=f"Score: {score}",
bg=BLUE_GRAY, fg="white",
font=('Arial', 10, "normal"),
textvariable=label_var, # the label will update whenever this var is 'set'
)

Related

Tkinter while loop guess game

# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
def submit():
tries = 5
while tries >= 0:
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()
I am trying to create a guessing game with Tkinter, I have created all the entries and labels, the clear button is working. I am struggling with creating a while loop, I need the program to stop accepting submitted entries once 5 tries have been used. Any ideas on how I can solve this?
Like already mentioned by #Paul Rooney, i also think that a while loop is a bad design for this. However, here is a working example with a global variable and some minor changes (disabling entry and button when 0 tries are reached):
# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
# define outside of function to not overwrite each time
tries = 5
def submit():
global tries # to make tries a global variable
while tries > 0: # this matches your tries amount correctly
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
# print status, disable the widgets
if tries == 0:
print("No more tries left")
guessE.configure(state="disabled")
submitBtn.configure(state="disabled")
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()

How can I limit pick a question from a list only once in a random order?

I am trying to modify my flashcard python script. It works fine, but what I am triying to do is to modify the random function so that a single question (and its answer) it is not chosen twice. The script should not continue picking questions after the list is completed. I would also need to add a button that let me brwose back to previuos selections.
Any suggestions?
from tkinter import *
from tkinter import ttk
from random import randint
root = Tk()
root.title('Domande')
root.geometry("850x400")
root.resizable(True, True)
words = [
(("Stadio Olimpico"), ("ROMA")),
(("Stadio Artemio Franchi"), ("FIORENTINA")),
(("Stadio Armando Picchi"), ("LIVORNO")),
(("Stadio Luigi Ferraris"), ("SAMPDORIA"))
(("Stadio Arechi"), ("SALERNITANA"))
]
# get a count of our wods list
count = len(words)
def next():
global hinter, hint_count
#Clear screen
answer_label.config(text="")
label.config(text="")
hint_label.config(text="")
#Reset Hint stuff
hinter = ""
hint_count = 0
#Create random selection
global random_domande
random_domande = randint(0, count-1)
#Update label with Domande
domande.config(text=words[random_domande][0])
#Keep track of the hint
hinter = ""
hint_count = 0
def hint():
global hint_count
global hinter
if hint_count < len(words[random_domande][1]):
hinter = hinter + words[random_domande][1][hint_count]
hint_label.config(text=hinter)
hint_count +=1
#Define function to hide the widget
def hide_widget(widget):
widget.pack_forget()
widget.config(text=words[random_domande][1])
#Define a function to show the widget
def show_widget(widget):
widget.pack()
widget.config(text=words[random_domande][1])
#Labels
domande = Label(root, text="", font=("Times", 14))
domande.pack(side=TOP)
#Create an Label Widget
label = Label(root, text="", font=("Times", 14))
label.pack()
#Create Buttons
button_frame = Frame(root)
button_frame.pack()
hint_button = Button(button_frame, text="Hint", command=hint)
hint_button.pack()
button_show = Button(root, text= "Show", command= lambda:show_widget(label))
button_show.pack()
#Create a button Widget
button_hide = Button(root, text= "Hide", command=lambda:hide_widget(label))
button_hide.pack()
next_button = Button(button_frame, text="Next", command=next)
next_button.pack()
#Create Hint Label
hint_label = Label(root, text="")
hint_label.pack()
answer_label = Label(root, text="", font=("Times", 14))
answer_label.pack(side=BOTTOM)
#Run next function when the program starts
next()
root.mainloop()

How to change the text of a Label - Tkinter

I am creating a math game and want a score count in the top corner.
Yes, you need the command argument, but you also need a function for the command argument to run. Something like this would work:
from tkinter import *
def increment_score():
global score
score += 1 # update variable
score_addition_easy_number.config(text=score) # update screen
root = Tk()
score = 0
root7 = Frame(root)
score_addition_easy_label = Label(root7, text="Score count: ")
score_addition_easy_label.pack(side=LEFT)
score_addition_easy_number = Label(root7, text=score)
score_addition_easy_number.pack(side=LEFT)
root7.pack()
a_e_answer_2 = Button(root, text="8", font=("times", 30, "bold"), padx=190, command=increment_score)
a_e_answer_2.pack()
root.mainloop()

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:

TKInter Python checkbutton state

I am trying to do some work on a text file if certain checkbuttons are checked.
"Populate CheckBoxes"
Label(master, text="Pick at least one index:").grid(row=4, column=1)
Checkbutton(master, text="Short",variable=var1).place(x=5,y=60)
Checkbutton(master, text="Standard",variable=var2).place(x=60,y=60)
Checkbutton(master, text="Long",variable=var3).place(x=130,y=60)
Calling
print("Short: %d,\nStandard: %d,\nLong: %d" % (var1.get(), var2.get(),
var3.get()))
prints out 0 or 1 for each variable but when I am trying to use that value to do something it does'nt seem to call the code.
if var2.get(): <--- does this mean if = 1?
Do something
In below example var.get()'s value is printed in command prompt if it's False and updates the lbl['text'] if it's True:
import tkinter
root = tkinter.Tk()
lbl = tkinter.Label(root)
lbl.pack()
var = tkinter.BooleanVar()
def update_lbl():
global var
if var.get():
lbl['text'] = str(var.get())
else:
print(var.get())
tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()
root.mainloop()
But below code never prints as "0" and "1" are both True:
import tkinter
root = tkinter.Tk()
lbl = tkinter.Label(root)
lbl.pack()
var = tkinter.StringVar()
def update_lbl():
global var
if var.get():
lbl['text'] = str(var.get())
else:
print(var.get())
tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()
root.mainloop()

Categories

Resources