Python 3.x 如何在函数内部使用变量而不将其声明为全局变量
我有一个两部分的问题,如果这是不允许的,我真的只需要回答第一部分 我有以下示例代码Python 3.x 如何在函数内部使用变量而不将其声明为全局变量,python-3.x,tkinter,Python 3.x,Tkinter,我有一个两部分的问题,如果这是不允许的,我真的只需要回答第一部分 我有以下示例代码 import tkinter as tk window = tk.Tk() def countIncrease(): count +=1 t1.insert(tk.END,count) count = 0 t1=tk.Text(window,height=3,width=30) t1.grid(row=0,column=0,columnspan=3) b1=tk.Button(window
import tkinter as tk
window = tk.Tk()
def countIncrease():
count +=1
t1.insert(tk.END,count)
count = 0
t1=tk.Text(window,height=3,width=30)
t1.grid(row=0,column=0,columnspan=3)
b1=tk.Button(window,text="+",height=3,width=10,command=countIncrease)
b1.grid(row=1,column=0)
window.mainloop()
如果我执行这段代码,就会得到UnboundLocalError错误:赋值前引用的局部变量'count'
我知道我可以简单地通过向函数添加全局计数来解决这个问题
在我这样做之后,当我按下按钮时,输出是1,重复按下会产生12、123、1234、12345等等
我的第一个也是主要的问题是,我知道将变量设置为全局变量是一种不好的做法。在不将count作为全局变量的情况下,使其工作的正确方法是什么
我的第二个问题是如何使屏幕刷新,使其只显示最新的变量,即不是123,而是3 如果不想使用全局变量,应该重新构造代码以使用类,并将count作为类变量。要“刷新”屏幕/tkinter文本,您需要在插入新内容之前删除内容 以下是解决这两个问题的一种方法:
import tkinter as tk
class app():
def __init__(self, parent):
self.count = 0
self.t1=tk.Text(parent, height=3,width=30)
self.t1.grid(row=0,column=0,columnspan=3)
self.b1=tk.Button(parent,text="+",height=3,width=10,command=self.countIncrease)
self.b1.grid(row=1,column=0)
def countIncrease(self):
self.count +=1
self.t1.delete('1.0', tk.END) #refresh/delete content of t1
self.t1.insert(tk.END,self.count)
window = tk.Tk()
app(window) # Create an instance of app
window.mainloop()
关于第一部分: