首页 > 解决方案 > 使用 Python 将返回值从一个函数传递到另一个函数

问题描述

我正在尝试将输入的值从一个函数传递到另一个函数。它的工作原理是用户单击运行该chk():功能的 Tkinter 按钮。单击按钮后,用户将必须扫描他们的标签(rfig 标签),该标签将读取用户的标签tagID并为idTag变量赋值。idTag返回时,dataCheck():将调用该函数并检查该值是否与我的 sqlite3 数据库的userID列中idTag的值之一匹配。

我的问题是我不断收到错误未定义名称'idTag'

该命令的reader.read()作用类似于输入函数,因为用户实际上必须扫描(或输入)他们的标签才能继续。我认为问题是在单击按钮后立即调用该函数,这导致idTag变量仍然为空,因为用户尚未输入值。有什么想法吗?

from tkinter import *
import sqlite3 as sql
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()

global idTag
   
# Tkinter button click Command 
def chk():

    # Function that handels getting User ID 
    def tagScanner(idTag):
        #Get user id value
        tagID = reader.read()
        #If tag is scanned 
        if tagID:
            idTag= (tagID,)
            return idTag
            #call Database function to check returned idTag
            dataCheck(idTag)
    
    # Function handels SQLite3 Database     
    def dataCheck(idTag):
        Database = sql.connect('MedaDataBase.db')
        # cursor
        c= Database.cursor()
        #Check if the idTag maches a value in the userID column of sqlite DB
        query = 'SELECT userID FROM Users "WHERE" userID = "idTag"'

        c.execute(query)
        c.fetchone()
           
        if query == idTag: #if userID is returned
            print('User Verified')
        else:
            print('Denied')
        Database.close()

    #Call scanning function 
    tagScanner(idTag)

标签: pythonsqliteraspberry-pirfid

解决方案


这里有几个问题

首先,摆脱global idTag我认为这只会造成范围问题。您不需要全局变量。

tagScanner()不使用它唯一的输入参数,所以去掉它。您从 获取 id reader,因此此函数不需要其他输入。

您将输入idTagdateCheck(idTag)查询字符串进行比较,而不是查询返回的任何内容,这可能不是您的意图。

当解释器到达return函数中的 a 时,函数退出。最后一行tagScanner()永远不会执行,因为它在此之前返回。dataCheck(idTag)在你回来之前试着打电话idTag

您的 sqlite 查询始终查询“idTag”,例如字符串“idTag”,而不是您读入并分配给变量的值idTag。用于?指定您要在查询期间提供值,请参阅此处的文档: https ://docs.python.org/2/library/sqlite3.html

把它们放在一起:

from tkinter import *
import sqlite3 as sql
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()

# Tkinter button click Command 
def chk():

    # Function that handels getting User ID 
    def tagScanner():
        # Get user id value
        idTag = reader.read()
        # If tag is scanned 
        if idTag:
            # call Database function to check returned idTag
            dataCheck(idTag)
            return idTag
    
    # Function handles SQLite3 Database     
    def dataCheck(idTag):
        Database = sql.connect('MedaDataBase.db')
        # cursor
        c = Database.cursor()
        # Check if the idTag maches a value in the userID column of sqlite DB
        query = 'SELECT userID FROM Users WHERE userID = ?'

        c.execute(query, (idTag,))
        row_returned = c.fetchone()
        if row_returned is not None:
            # Found a matching row
            print('User Verified')
        else:
            print('Denied')
        Database.close()

    # Call scanning function 
    tagScanner()

推荐阅读