首页 > 解决方案 > 使用 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 天,没有任何答案,我准备放弃它。

标签: pythontkinter

解决方案


我对功能进行了必要的更改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()

推荐阅读