无法访问已声明的全局变量

时间:2019-09-13 15:51:00

标签: python tkinter global-variables nameerror

我尝试声明一个全局变量来存储返回的数据库对象。但是它引发了NameError异常。 尝试将返回的对象声明为全局对象,但没有发生任何有用的事情。

import tkinter as tk
import mysql.connector
import tkinter.messagebox
# import connect

root = tk.Tk()
root.title("Login To Database")
root.geometry("400x160")
root.resizable(width=False, height=False)

connectFrame = tk.Frame()
connectFrame.pack()

# Defining Functions


def unhidePassword():
    if (checked.get()):
        passwordEntry.configure(show="")
    elif (not checked.get()):
        passwordEntry.configure(show="*")


def createConnection():
    try:
        global db
        db = mysql.connector.connect(
            user=user.get(),
            host=host.get(),
            password=password.get(),
            database=database.get(),
            auth_plugin='mysql_native_password'
        )
        tkinter.messagebox.showinfo(message="Connection Created Successfully")

    except mysql.connector.errors.ProgrammingError:
        tkinter.messagebox.showerror(
            message="Incorrect Data Entered")


# Creating Widgets

# introLabel = tk.Label(connectFrame, text="Connect To Database",
#                      padx = 15, pady = 10, bg = "#42caff")


userName_label = tk.Label(connectFrame, text="User Name: ")
user = tk.StringVar()
userName_entry = tk.Entry(connectFrame, bd=1, width=27, textvariable=user)

hostLabel = tk.Label(connectFrame, text="Host: ")
host = tk.StringVar()
hostEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=host)


passwordLabel = tk.Label(connectFrame, text="Password: ")
password = tk.StringVar()
passwordEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=password)
checked = tk.IntVar()  # For checking if check button is checked or not
showPass = tk.Checkbutton(connectFrame, variable=checked,
                          text="Show Password", command=unhidePassword)


dataBaseLabel = tk.Label(connectFrame, text="Database:  ")
database = tk.StringVar()
dataBaseEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=database)

connectBtn = tk.Button(
    connectFrame, text="Connect To Database", cursor="hand2", bd=0, bg="#0ffcdd", command=lambda: createConnection())
curosr = db.cursor()
curosr.execute("SELECT * FROM visitors")
print(curosr.fetchall())


userName_label.grid(row=0, column=0)
userName_entry.grid(row=0, column=1)

hostLabel.grid(row=1, column=0)
hostEntry.grid(row=1, column=1)

passwordLabel.grid(row=2, column=0)
passwordEntry.grid(row=2, column=1)
passwordEntry.configure(show="*")
showPass.grid(row=2, column=2, ipadx=20)

dataBaseLabel.grid(row=4, column=0)
dataBaseEntry.grid(row=4, column=1)

connectBtn.grid(row=7, column=1, pady=15, ipady=5)


root.mainloop()

尝试将返回的对象声明为全局对象,但仍显示未定义的错误。但是,我的编辑器可以访问方法和属性。谁能解释这是什么?

1 个答案:

答案 0 :(得分:0)

为运行脚本,我进行了一些更改。

  • 将MySQLdb导入为mdb
  • 导入系统

所以您的脚本看起来像

 import tkinter as tk
import MySQLdb as mdb
import tkinter.messagebox
import sys

root = tk.Tk()
root.title("Login To Database")
root.geometry("400x160")
root.resizable(width=False, height=False)


connectFrame = tk.Frame()
connectFrame.pack()

# Defining Functions


def unhidePassword():
    if (checked.get()):
        passwordEntry.configure(show="")
    elif (not checked.get()):
        passwordEntry.configure(show="*")


def createConnection():
    try:
        global db
        db = mdb.connect(
            user=user.get(),
            host=host.get(),
            password=password.get(),
            database=database.get(),
            auth_plugin='mysql_native_password'
        )
        tkinter.messagebox.showinfo(message="Connection Created Successfully")

    except :
        msg = (sys.exc_info()[1],
                       sys.exc_info()[0],
                       sys.modules[__name__])
        print(msg)
        #tkinter.messagebox.showerror(msg)


# Creating Widgets

# introLabel = tk.Label(connectFrame, text="Connect To Database",
#                      padx = 15, pady = 10, bg = "#42caff")


userName_label = tk.Label(connectFrame, text="User Name: ")
user = tk.StringVar()
userName_entry = tk.Entry(connectFrame, bd=1, width=27, textvariable=user)

hostLabel = tk.Label(connectFrame, text="Host: ")
host = tk.StringVar()
hostEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=host)


passwordLabel = tk.Label(connectFrame, text="Password: ")
password = tk.StringVar()
passwordEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=password)
checked = tk.IntVar()  # For checking if check button is checked or not
showPass = tk.Checkbutton(connectFrame, variable=checked,
                          text="Show Password", command=unhidePassword)


dataBaseLabel = tk.Label(connectFrame, text="Database:  ")
database = tk.StringVar()
dataBaseEntry = tk.Entry(connectFrame, bd=1, width=27, textvariable=database)

connectBtn = tk.Button(connectFrame, text="Connect To Database", cursor="hand2", bd=0, bg="#0ffcdd", command=lambda: createConnection())




userName_label.grid(row=0, column=0)
userName_entry.grid(row=0, column=1)

hostLabel.grid(row=1, column=0)
hostEntry.grid(row=1, column=1)

passwordLabel.grid(row=2, column=0)
passwordEntry.grid(row=2, column=1)
passwordEntry.configure(show="*")
showPass.grid(row=2, column=2, ipadx=20)

dataBaseLabel.grid(row=4, column=0)
dataBaseEntry.grid(row=4, column=1)

connectBtn.grid(row=7, column=1, pady=15, ipady=5)


root.mainloop()

所以当您尝试连接时,您会看到sys报告的错误

(TypeError("'auth_plugin' is an invalid keyword argument for connect()"), <class 'TypeError'>, <module '__main__' (built-in)>)

如果您删除此行

 auth_plugin='mysql_native_password'

脚本应该可以工作。

但是,这不是您想要做的正确方法。