首页 > 解决方案 > 如何在 tkinter 中按下按钮后立即更改值?

问题描述

当按下摇滚按钮时,我希望你的分数在你按下按钮后立即上升一分。然而,分数会在按下按钮后更新,而不是在按下一个按钮后立即更新。要明白我的意思,按两次摇滚按钮,你会得到 1 分。我将如何解决这个问题?

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()
 

标签: pythonbuttontkinter

解决方案


我已经尝试过使用您的代码,但我不确定您要实现什么,所以如果我错了,请原谅我。我认为有两种方法可以实现我认为你想要的。

方式1(不改变你的功能代码):

现在只需更改your_score = 0为即可your_score = 1解决此问题。

方式 2(更改函数内部,重新排列代码):

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)

如果有任何错误或疑问,请告诉我:D


推荐阅读