python - 使用 Python (Tkinter) 的计数方法
问题描述
我从这篇文章中得到了动力:在 Tkinter 标签中每秒增加数字 +1
所以我决定用 Tkinter 做一个记分牌,我要拔头发了,因为我知道这是一个基本问题,答案很可能很明显,我就是想不通。
它是一个足球记分牌。由4个按钮组成
score_dict = {"Touchdown": 6, "Extra Point": 1, 'Field Goal': 3, "Conversion": 2, "Safety": 2}
每次我点击按钮时,我都希望标签反映分数,但我不知道如何保留之前的标签数量并添加到它。
因此,如果标签显示为 6,并且我添加了一个射门得分,它应该显示为 10,而不是重新开始。
# Creating label + buttons and putting them on screen
label = Label(root, text=0)
buttons = [Button(root, text=i, command=lambda i=i: press(i)) for i in score_dict.keys()]
for i in range(len(buttons)):
buttons[i].grid(row=1, column=i)
label.grid(row=0, column=2)
# press function from button list comprehension:
def press(i):
global label
if score_dict[i] == 6:
if label['text'] < score_dict[i]:
label['text'] += 1
root.after(100, press, i)
if score_dict[i] == 1:
if label['text'] < score_dict[i]:
label['text'] += 1
root.after(100, press, i)
if score_dict[i] == 3:
if label['text'] < score_dict[i]:
label['text'] += 1
root.after(100, press, i)
if score_dict[i] == 2:
if label['text'] < score_dict[i]:
label['text'] += 1
root.after(100, press, i)
问题在于 if 语句。当我按下按钮一次时,只要分数超过标签读取的分数,它就不符合任何条件,但我不确定如何表达它。
我在 Reddit 上发布了 5 天,没有任何答案,我准备放弃它。
解决方案
我对功能进行了必要的更改press
。代码需要一个工作字典来跟踪分数和一个静态字典来重置测试语句。
总分在标签中。
import tkinter as tk
score_dict = {"Touchdown": 6, "Extra Point": 1,
"Field Goal": 3, "Conversion": 2,
"Safety": 2}
working_dict = score_dict.copy()
root = tk.Tk()
label = tk.Label(root, text = 0)
label.grid(sticky = tk.NSEW)
def press(i):
if working_dict[i] > 0:
working_dict[i] -= 1
label['text'] += 1
root.after(100, press, i)
else:
working_dict[i] = score_dict[i]
buttons = [tk.Button(root, text = i, command = lambda i = i: press(i)) for i in score_dict.keys()]
for i in range(len(buttons)):
buttons[i].grid(row = 1, column = i)
root.mainloop()
推荐阅读
- python - 如何在其属性上找到具有相同函数返回值的列表中的两项?
- javascript - 使用相应的复选框 jquery 启用禁用输入文本
- javascript - React - getDerivedStateFromProps 是否需要返回所有状态属性?
- excel - 如何将三个单元格中的多个值返回到 Excel 中的一个单元格中?我需要返回一个值
- r - Lambda 问题或交叉验证
- r - 如何使用我自己的词典来分析 R 中的句子?
- php - 没有语法错误的 PHP 脚本不会完全解析
- swift - AWS Mobile Hub 声明用户在自定义 UI 用户池登录/身份验证后未登录
- java - Java forEach 无法使用 IntStream.range 处理 flatMap
- arrays - 使用数组嵌套 For 循环以分配变量