首页 > 解决方案 > 通过单击另一个按钮来更改按钮的文本?

问题描述

每当我单击检测按钮时,我都希望更新0/1000按钮。当我单击它一次时,它变成1/1000。如果我单击它两次,它会变成2/1000,依此类推。我该怎么做?我有这个到目前为止,它没有工作。

from tkinter import *
from tkinter import ttk

score = 0
max_score = 1000

root = Tk()
root.title('Gamerscore')
root.geometry('600x400')
root.grid_rowconfigure(0, weight='1')
root.grid_columnconfigure(0, weight='1')

style = ttk.Style()
style.configure("TButton",
                font="Serif 15",
                padding=10)


def button_detect_press():
    score += 1
    button_score = ttk.Button(main_frame, text=str(score) + '/' + str(max_score)).grid(row=1, column=0)


main_frame = Frame(root)
main_frame.grid(row=0, columnspan=4)

button_score = ttk.Button(main_frame, text=str(score) + '/' + str(max_score)).grid(row=1, column=0)
button_detect = ttk.Button(main_frame, text='Detect', command=button_detect_press).grid(row=4, column=0)

root.mainloop()

标签: python-3.xtkinter

解决方案


问题是您在每次点击时都会创建一个新按钮。相反,您想configure在现有按钮上调用该方法。

这需要两个改变。首先,您需要将按钮的创建与其布局分开。这是必要的,因为ttk.Button(...).grid(...)返回 的值grid(...),并且总是返回 None。另外,根据我的经验,将它们分开可以使布局在阅读代码时更容易可视化,并且更容易编写代码。

因此,像这样创建和布局按钮:

button_score = ttk.Button(main_frame, text=str(score) + '/' + str(max_score))
button_detect = ttk.Button(main_frame, text='Detect', command=button_detect_press)

button_score.grid(row=1, column=0)
button_detect.grid(row=4, column=0)

接下来,修改button_detect_press以调用configureon 的方法button_score。另外,因为您正在修改score它,所以需要将其声明为全局:

def button_detect_press():
    global score
    score += 1
    text = str(score) + '/' + str(max_score))
    button_score.configure(text=text)

推荐阅读