简体   繁体   中英

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. 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. 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

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM