如何解决Tkinter中按钮点击后整数变量重置为初始值的问题
问题原因
你遇到的问题核心是变量传递方式和作用域的问题:
- 当你把
total_votes作为参数传给voting方法时,传递的是变量的值拷贝,不是引用。所以tv +=1只是修改了方法内部的局部变量tv,完全不会影响全局的total_votes。 - 每次点击按钮时,
lambda表达式里的total_votes都会重新获取全局初始值15,导致每次点击都从15开始加1,看起来像是重置了。
解决方案
这里提供两种简洁的解决思路:
方法一:使用全局变量直接修改
修改voting方法,通过global关键字声明要使用全局的total_votes,直接修改它:
import tkinter as tk total_votes = 15 root = tk.Tk() class VoteButton: def __init__(self, row, column, text): self.row = row self.column = column self.text = text # 不需要传递total_votes参数 self.vbtn = tk.Button(root, text=self.text, command=self.voting) def draw(self): self.vbtn.grid(row=self.row, column=self.column) def voting(self): global total_votes # 声明使用全局变量 total_votes += 1 print(total_votes) btn = VoteButton(0, 0, "button") btn.draw() btn2 = VoteButton(0, 1, "button") btn2.draw() root.mainloop()
方法二:用可变对象存储票数(避免全局变量)
如果不想用全局变量,可以把票数放在一个可变对象里(比如列表),因为可变对象传递的是引用,修改内部值会影响原对象:
import tkinter as tk # 用列表存储票数,列表是可变对象 total_votes = [15] root = tk.Tk() class VoteButton: def __init__(self, row, column, text, vote_counter): self.row = row self.column = column self.text = text self.vote_counter = vote_counter self.vbtn = tk.Button(root, text=self.text, command=self.voting) def draw(self): self.vbtn.grid(row=self.row, column=self.column) def voting(self): self.vote_counter[0] += 1 print(self.vote_counter[0]) btn = VoteButton(0, 0, "button", total_votes) btn.draw() btn2 = VoteButton(0, 1, "button", total_votes) btn2.draw() root.mainloop()
说明
- 方法一简单直接,适合小型程序;
- 方法二更符合面向对象的封装思想,避免全局变量带来的耦合问题,适合复杂一点的程序。
内容的提问来源于stack exchange,提问作者mr. bug
相关产品推荐
相关产品推荐

