如何使用变量的函数内没有宣布它作为一个全局变量

问题描述:

我有一个2部分的问题(如果那是不允许的,我真的只需要回答第一部分)如何使用变量的函数内没有宣布它作为一个全局变量

我有下面的示例代码

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: local variable 'count' referenced before assignment

我知道,我可以简单地通过增加global count的功能解决这个问题

当我这样做后,当我按下按钮时,输出为1,重复按产生12,123,1234,12345等等。

我的第一个(也是主要的)问题是,我知道把变量变成全局是不好的做法。做这项工作的正确方法是什么,而不要把它算作一个全局变量?

我的第二个问题是如何使屏幕上显示“刷新”,所以它是只显示最新的变量,即而不是123它只是3

+0

关于第一部分:(https://*.com/questions/ [在Tkinter的其他功能使用从进​​入/按钮变量] 20771627 /使用最可变从进入键合另一功能合Tkinter的) – Lafexlos

你应该调整你的代码使用class和如果您不想使用global变量,请将count作为类变量。为了刷新屏幕/ tkinter text,您需要在插入新内容之前删除内容。

这里有一个办法可以解决两个问题:

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()