I have a script that looks like this
import tkinter as tk
from random import randint
a=[]
b=[]
c={}
d={}
def program():
a.append(1)
c[randint(10, 20)] = randint(0, 10)
do_something()
do_something_else()
print(a)
print(b)
print(c)
print(d)
print('done')
return
def do_something():
b.append(15)
return
def do_something_else():
d[randint(10, 20)] = randint(0, 10)
return
root = tk.Tk()
tk.Button(root, text="Run", command=program).pack()
root.mainloop()
The problem here is clicking the button runs the function program()
again with the previous values in the lists and dictionaries and so they are just appended. I want an empty dicts and lists everytime program()
is called.
I created a function to do just that.
def empty():
global a,b,c,d
a=[]
b=[]
c={}
d={}
return
Ive seen much talk about not using global
in functions. What would be a neat way to achieve this?
CodePudding user response:
Just make the variables local to program()
and pass them around:
import tkinter as tk
from random import randint
def program():
a=[]
b=[]
c={}
d={}
a.append(1)
c[randint(10, 20)] = randint(0, 10)
do_something(b)
do_something_else(d)
print(a)
print(b)
print(c)
print(d)
print('done')
def do_something(b):
b.append(15)
def do_something_else(d):
d[randint(10, 20)] = randint(0, 10)
root = tk.Tk()
tk.Button(root, text="Run", command=program).pack()
root.mainloop()
Now each call to program()
starts with new collections.