Reputation: 43
I need to return data from a function that is called by a tkinter button.
root= Tk()
def random():
num_1= random.randint(0,12)
num_2= random.randint(0,3)
return num_1,num_2
num_1= None
num_2= None
Play=ttk.Button(text="Play",command=random)
Play.grid(row=3,column=0)
root.mainloop()
Im not sure where the return actual stored the variables because when i print num_1 and num_2 both print None instead of the expected random numbers. Any input will be appreciated.
(also i have a mainloop etc.)
Upvotes: 0
Views: 192
Reputation: 129
Prefer do not use global variables
from tkinter import *
import random
def random_(tmp_list):
tmp_list[0] = random.randint(0, 12)
tmp_list[1] = random.randint(0, 3)
root = Tk()
tmp_list = [None, None]
Play=Button(text='Play', command=lambda: random_(tmp_list))
Play.grid(row=3, column=0)
root.mainloop()
print(tmp_list[0], tmp_list[1])
Upvotes: 0
Reputation: 712
You probably has a mistake as it seems you import random module
and called your callback function random
too.
Another cause for the issue here is that you affect local variables instead of global ones.
Upvotes: 0
Reputation: 65
do what you want the function to do inside the function in this scenario.
from tkinter import *
import random
root= Tk()
def random_():
num_1= random.randint(0,12)
num_2= random.randint(0,3)
# return num_1,num_2
print(num_1,num_2)
num_1= None
num_2= None
Play= Button(text="Play",command=random_)
Play.grid(row=3,column=0)
root.mainloop()
return
would work if you do
print(random_)
Upvotes: 1
Reputation: 804
if you meant to declare num_1
and num_2
as global variable then you should declare it in random function.
root= Tk()
def random():
global num_1, num_2
num_1= random.randint(0,12)
num_2= random.randint(0,3)
return num_1,num_2
num_1= None
num_2= None
Play=ttk.Button(text="Play",command=random)
Play.grid(row=3,column=0)
root.mainloop()
Upvotes: 1