首页 > 解决方案 > 单击时如何修复数字不变

问题描述

当脚本启动时,将出现一个标题为 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()

标签: pythontkinter

解决方案


尝试使用一些 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()

推荐阅读