[英]How to return a value from one function to other using a button in tkinter
So, I am working on a project in which there is a login screen with option to type in the id and password, but then in the GUI I want that when the "Enter" button is clicked, it should return the id to the function where is is called.所以,我正在做一个项目,其中有一个登录屏幕,可以选择输入 id 和密码,但是在 GUI 中我希望当单击“Enter”按钮时,它应该将 id 返回到 function在哪里被称为。 My program is too long so I will give a small example to clear my point.
我的程序太长了,所以我将举一个小例子来说明我的观点。
def func3():
cred = func1()
print(cred)
def func1(): #Function for creating the GUI
root = Tk()
def func2(): #Function for getting the data and comparing with data from MySQL
id = '123' #from entry widget
flag = 0
# Comparison done: flag now equals 0 or 1
if flag == 1: #When data matches
return id
btn = Button(master=root,text="Enter",command=func2) #This button should compare and return the id
btn.pack()
From what I have understood, you are looking for something like this据我了解,您正在寻找这样的东西
from tkinter import *
def verify():
global id_
id_=id_entry.get()
if id_==ID and pass_entry.get()==PASS:
print('Success')
else:
print('Invalid')
root=Tk()
id_entry=Entry(root)
id_entry.pack()
pass_entry=Entry(root)
pass_entry.pack()
ent_button=Button(root,text='Enter',command=verify)
ent_button.pack()
ID='example'
PASS='password'
root.mainloop()
Using retrun
will be pointless in this case since callbacks can't really return anything.在这种情况下使用
retrun
将毫无意义,因为回调不能真正返回任何东西。 It has been explained well in this post.在这篇文章中已经很好地解释了。
UPDATE更新
If you declare the variable as global
, you can access it from anywhere in the code如果将变量声明为
global
,则可以从代码中的任何位置访问它
def verify():
global id_
id_=id_entry.get()
if id_==ID and pass_entry.get()==PASS:
success()
else:
print('Invalid')
def success():
print(id_,'logged in successfully')
If you don't want to use global
then you can pass it to the target function如果您不想使用
global
,则可以将其传递给目标 function
def verify():
id_=id_entry.get()
if id_==ID and pass_entry.get()==PASS:
success(id_)
else:
print('Invalid')
def success(id_):
print(id_,'logged in successfully')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.