通过单击另一个按钮来更改按钮的文本?

时间:2019-07-22 22:42:50

标签: python-3.x tkinter

每当我单击检测按钮时,我都希望更新 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()

1 个答案:

答案 0 :(得分:3)

问题是您每次点击都会创建一个新按钮。而是要在现有按钮上调用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以在configure上调用button_score方法:

def button_detect_press():
    score += 1
    text = str(score) + '/' + str(max_score))
    button_score.configure(text=text)
相关问题