python-3.x - 通过单击另一个按钮来更改按钮的文本?
问题描述
每当我单击检测按钮时,我都希望更新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()
解决方案
问题是您在每次点击时都会创建一个新按钮。相反,您想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
on 的方法button_score
。另外,因为您正在修改score
它,所以需要将其声明为全局:
def button_detect_press():
global score
score += 1
text = str(score) + '/' + str(max_score))
button_score.configure(text=text)
推荐阅读
- android - 使用 Gradle 插件 v4.10.1 重命名 Apk
- angular - jspdf 上显示奇怪的字符(þÿ)
- javascript - 参数未传递任何内容或传递 null
- signature - 如何获取先前导入到 Windows Cert: 存储(在 Delphi 中)的公共证书的 CNG 密钥句柄?
- git - 致命:在执行 git fetch repo_b master 时 repo_b 的身份验证失败(当前在 repo_a 的 master 上,它是从 repo_b 分叉的)
- php - 在搜索和用户代理中尝试 php hack/inject:“print(238947899389478923-34567343546345)”
- javascript - Javascript(ES6)从数组中选择/过滤对象并将它们从原始数组中删除的方法
- python - argparse 和互斥的命令行参数
- spring - 如何将此 POST cURL 请求转换为 java 代码
- python - 如何计算给定分布的值的可能性?