python - 如何在 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()
解决方案
我已经尝试过使用您的代码,但我不确定您要实现什么,所以如果我错了,请原谅我。我认为有两种方法可以实现我认为你想要的。
方式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
推荐阅读
- mysql - Laravel - 块更新太慢(SQLSRV - MYSQL)
- time - 如何计算 SAS 中 HTD(半年截止日期)的开始日期和结束日期?有没有像 intck 或 intnx 这样的功能可以帮助我的情况?
- c# - C#如何在数字右侧显示2dim数组
- c - 下面的 C 中二进制代码 Es 中的 ASCII 代码是我的代码,但它不起作用...在输出中我需要像 [C 067: 01000011]
- mysql - 小组再见 Mysql 8
- php - 如何使用 PHP 将数组打印到 XML
- javascript - 尝试将对象推送到数组时出现打字稿“padStart”错误
- reactjs - 找不到模块“D:\Resources\DevOps\eslint\bin\eslint.js”
- typescript - 如何使用 Jest 和 Typescript 模拟 PouchDb 数据库?
- android - new HTTPConnection1.execute() 中的编译器错误;其中 HTTPConnection1 类扩展了 AsyncTask