snaktastic
snaktastic

Reputation: 43

return data from a function called by tkinter button

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

Answers (4)

nick nick
nick nick

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

Sylvan LE DEUNFF
Sylvan LE DEUNFF

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

Mohamed
Mohamed

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

Farbod Shahinfar
Farbod Shahinfar

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

Related Questions