python - 单击时如何修复数字不变
问题描述
当脚本启动时,将出现一个标题为 Test 的按钮。应该发生的是,当您单击它时,将出现一个带有单击次数的消息框。但由于某种原因,这个数字并没有上升。这发生在第 9 行和第 10 行。
import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
top = Tk()
top.geometry("200x100")
clicks = 0
text = "Clicks:", clicks + 1
def fun():
tk.messagebox.showinfo("Test", text)
b1 = Button(top,text = "Test",command = fun,foreground = "black",background = "lightgray",activeforeground = "black",activebackground = "darkgrey",pady=50,padx=100)
b1.pack(side = TOP)
top.mainloop()
解决方案
尝试使用一些 OOP:
import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
class MyClick:
def __init__(self):
self.clicks = 0
top = Tk()
top.geometry("200x100")
def fun(my_click):
my_click.clicks += 1
tk.messagebox.showinfo("Test", f'Clicks: {my_click.clicks}')
my_click = MyClick()
b1 = Button(top, text="Test", command=lambda: fun(my_click), foreground="black", background="lightgray",
activeforeground="black", activebackground="darkgrey", pady=50, padx=100)
b1.pack(side=TOP)
top.mainloop()
推荐阅读
- swiftui - 仅在明确声明后显示 Date() 文本
- html - 我怎样才能让我的垂直css选框重复
- string - Oracle - 将字符串与等式子句中的变量连接起来
- c++ - 如何在 macOS 上使用 Makefile?
- spring - 如何在存储库中使用 Spring Boot JPA / Hibernate 进行内部联接?
- javascript - 如何从Javascript中的对象数组中提取特定值?
- c# - ASP.NET Core 模型验证错误以错误的顺序显示
- wordpress - 如何从 Wordpress Polylang 中删除类别 URL
- java - 如何将超链接添加到 Java SWT 标签
- reactjs - 使用样式化组件对 Jest 进行本机测试