简体   繁体   中英

How to get a value to change immediately after a button is pressed in tkinter?

When the rock button is pressed I want your score to go up by one immediately after you press the button. However the score updates on the button press after instead of immediately updating after one button press. To see what I mean press the rock button twice and you will get a score of 1. How would I fix this problem?

from tkinter import *
import random


root = Tk()
results = Label(root)
your_score = 0

def rock_input():
    global results
    global your_score

    options = ['scissors']
    cpu = random.choice(options)

    win = Label(root, text='you win!!!')
    human_score = Label(root, text='Your score: ' + str(your_score))

    win.config(font=('Courier', 44))
    human_score.config(font=('Courier', 15))
    results.grid_forget()

    if cpu == 'scissors':
        your_score += 1
        human_score.grid(row=2, column=1)
        results = win
        results.grid(row=4, column=0)


rock_button = Button(root, text='rock', bg='#a85032', padx=20, pady=15, command=rock_input)
rock_button.grid(row=1, column=0)

root.mainloop()
 

I have tried playing around with your code and im not sure what you're trying to achieve, so pardon me if im wrong. I think there is two ways to achieve what i think you want.

Way 1 (does not change your function code):

Simply changing your_score = 0 to your_score = 1 will fix the issue for now.

Way 2 (change inside your function, rearranging the code):

def rock_input():
    global results
    global your_score

    options = ['scissors']
    cpu = random.choice(options)
    if cpu == 'scissors':
        your_score += 1
        win = Label(root, text='you win!!!')
        human_score = Label(root, text='Your score: ' + str(your_score))

        win.config(font=('Courier', 44))
        human_score.config(font=('Courier', 15))
        results.grid_forget()

        human_score.grid(row=2, column=1)
        results = win
        results.grid(row=4, column=0)

Let me know if any errors or doubts:D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM