问题描述
我正在尝试将输入的值从一个函数传递给另一个函数。用户如何运行Tkinter按钮即可运行chk():
功能。单击该按钮后,用户将不得不扫描其标签(rfig标签),该标签将读取用户的tagID
并为idTag
变量提供一个值。返回idTag
时,将调用dataCheck():
函数,并检查idTag
的值是否与sqlite3数据库的 userID 列中的值之一匹配。
命令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()
不使用其唯一的输入参数,因此请摆脱它。您是从reader
获取ID的,因此此函数不需要其他输入。
您正在将idTag
中的输入dateCheck(idTag)
与查询字符串进行比较,而不是查询返回的内容,这可能不是您的意图。
当解释器到达函数中的return
时,该函数退出。 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()