Python UnboundLocalError:局部变量';名称(u chk)x27 ;;分配前参考
我用Python中的Tkinter和MySQL创建了一个银行管理系统Python UnboundLocalError:局部变量';名称(u chk)x27 ;;分配前参考,python,variables,tkinter,Python,Variables,Tkinter,我用Python中的Tkinter和MySQL创建了一个银行管理系统 def deposit_acc_chk(): mycursor.execute("SELECT name FROM bank_master WHERE acno = '"+deposit_entry1.get()+"'") for x in mycursor: name_chk = ''.join(map(str, x)) deposit_chk_entry.delete(0,
def deposit_acc_chk():
mycursor.execute("SELECT name FROM bank_master WHERE acno = '"+deposit_entry1.get()+"'")
for x in mycursor:
name_chk = ''.join(map(str, x))
deposit_chk_entry.delete(0, "end")
deposit_chk_entry.insert(0, name_chk)
deposit_chk_entry["state"] = "disabled"
此代码段显示存款账户持有人的姓名。它最初工作正常,但后来显示出一个错误
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\HP\Desktop\BMS - GUI v1.1.2.py", line 196, in deposit_acc_chk
deposit_chk_entry.insert(0, name_chk)
UnboundLocalError: local variable 'name_chk' referenced before assignment
我试图明确地将变量name\u chk
声明为全局变量,甚至尝试引用一些已经回答过的此类问题,但没有多大帮助。
我的错误仍未解决!请帮帮我
我是新来的,所以如果我没有正确描述我的问题,请原谅 你应该
- 在行之前声明
变量(这样也会进行初始化)name\u chk
如存款项。插入(0,名称项)
import tkinter as tk root = tk.Tk() name_chk = tk.StringVar()
- 在该函数结束和
行
以产生变量的定义存款项目。插入(0,名称项目)
在该函数中name\u chk
name\u chk
在更新存款记录之前,您应该检查是否有返回的记录:
def deposit_acc_chk():
mycursor.execute('SELECT name FROM bank_master WHERE acno = %s', (deposit_entry1.get(),))
rec = mycursor.fetchone()
if rec:
deposit_chk_entry['state'] = 'normal'
deposit_chk_entry.delete(0, 'end')
deposit_chk_entry.insert(0, rec[0])
deposit_chk_entry['state'] = 'disabled'
如果找不到记录,最好向用户显示:
def deposit_acc_chk():
mycursor.execute('SELECT name FROM bank_master WHERE acno = %s', (deposit_entry1.get(),))
rec = mycursor.fetchone()
name_chk = rec[0] if rec else '*** No record found ***'
deposit_chk_entry['state'] = 'normal'
deposit_chk_entry.delete(0, 'end')
deposit_chk_entry.insert(0, name_chk)
deposit_chk_entry['state'] = 'disabled'
这是因为SQL语句不返回任何记录,所以不会创建
name\u chk
。