python - 使用 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)
解决方案
这里有几个问题
首先,摆脱global idTag
我认为这只会造成范围问题。您不需要全局变量。
tagScanner()
不使用它唯一的输入参数,所以去掉它。您从 获取 id reader
,因此此函数不需要其他输入。
您将输入idTag
与dateCheck(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()
推荐阅读
- arrays - 查找数组右侧最远的较小数字的索引
- node.js - 尝试发布nodejs时未定义
- c - 使用 fscanf 忽略“=”字符
- vue.js - 为什么即使在向 mapmyindia apis 端点发出 POST 请求时在 VueJs 中启用代理设置后,我也会收到 CORS 错误?
- c# - 当新值是来自另一个集合的计算结果时,如何有效地更新 MongoDB 中超过 100K 的项目
- java - 使用 completablefuture 异步运行方法
- typescript - TS2345 编译 Vuetify 组件时出错 (VCalendar)
- python - Hubspot API 未填充交易
- python - python中的纵向数据分析
- java - 有没有办法进行 Datepicker 回合?(JavaFX)