[英]return data from a function called by tkinter button
I need to return data from a function that is called by a tkinter button. 我需要从tkinter按钮调用的函数返回数据。
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. 我不确定返回值实际存储在哪里变量,因为当我打印num_1和num_2时都打印None而不是预期的随机数。 Any input will be appreciated.
任何输入将不胜感激。
(also i have a mainloop etc.) (我也有一个mainloop等)
if you meant to declare num_1
and num_2
as global variable then you should declare it in random function. 如果您打算将
num_1
和num_2
声明为全局变量,则应在随机函数中声明它。
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()
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_)
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])
You probably has a mistake as it seems you import random module
and called your callback function random
too. 您可能有一个错误,因为您似乎导入了
random module
并且也将您的回调函数也称为random
。
Another cause for the issue here is that you affect local variables instead of global ones. 造成此问题的另一个原因是,您影响局部变量而不是全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.