[英]Passing returned value from one function to another with Python
我試圖將輸入的值從一個函數傳遞到另一個函數。 它的工作原理是用戶單擊運行chk():
函數的 Tkinter 按鈕。 一旦按鈕點擊,用戶將需要掃描的標簽(標簽rfig),將讀取用戶的tagID
和賦予idTag
變量的值。 當idTag
返回dataCheck():
函數將被調用,並檢查idTag
在我的sqlite3數據庫的用戶ID列中的值的值匹配之一。
我的問題是我不斷收到錯誤:未定義名稱“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()
不使用它唯一的輸入參數,所以去掉它。 您從reader
獲取 id ,因此此函數不需要其他輸入。
您將dateCheck(idTag)
的輸入idTag
與您的查詢字符串進行比較,而不是查詢返回的任何內容,這可能不是您的意圖。
當解釋器在函數中return
時,函數退出。 tagScanner()
的最后一行永遠不會執行,因為它在此之前返回。 在返回idTag
之前嘗試調用dataCheck(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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.