首页 > 解决方案 > 为什么我得到的对象在 python tkinter 中没有属性错误

问题描述

import tkinter as tk
import mysql.connector

conn = mysql.connector.connect(host='localhost', username='root', password='admin')
my_cursor = conn.cursor()


my_cursor.execute("CREATE DATABASE IF NOT EXISTS EMPLOYEE")
my_cursor.execute("USE EMPLOYEE")
my_cursor.execute("CREATE TABLE IF NOT EXISTS EMPLOYEE_DATA(ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(255), SALARY INT)")


def save_data():
    query_insert = "INSERT INTO EMPLOYEE VALUES(%s, %s)", (createNewWindow.lbname_entry.get(), createNewWindow.lbsalary_entry.get())
    my_cursor.execute(query_insert)
    conn.commit()

root = tk.Tk()
root.title("Monthly Pay")
root.geometry('440x550')
root.resizable(0,0)


def createNewWindow():
    newWindow = tk.Toplevel()
    newWindow.title("Monthly Pay")
    newWindow.geometry('440x550')
    newWindow.resizable(0, 0)

    lb2 = tk.Label(newWindow, text='NEW ENTRY', font=('Calibri (Body)', 30))
    lb2.pack()

    lbname = tk.Label(newWindow, text='NAME:', font=(10))
    lbname.place(x=10 ,y=80)

    lbname_entry = tk.Entry(newWindow)
    lbname_entry.place(x=110, y=82)

    lbsalary = tk.Label(newWindow, text='SALARY:', font=(10))
    lbsalary.place(x=10, y=120)

    lbsalary_entry = tk.Entry(newWindow)
    lbsalary_entry.place(x=110, y=122)


    btn1 = tk.Button(newWindow, text='SAVE', command=save_data)
    btn1.place(x=180, y=200)

lbl = tk.Label(root, text = 'MONTHLY PAY', font = ('Calibri (Body)', 35))
lbl.pack()

btn1 = tk.Button(root, text = 'New Employee', command = createNewWindow)
btn1.place(x=180 ,y=200)



root.mainloop()

错误

File "C:/Users/RISHI/PycharmProjects/untitled/monthy_pay.py", line 14, in save_data
    query_insert = "INSERT INTO EMPLOYEE VALUES(%s, %s)", (createNewWindow.lbname_entry.get(), createNewWindow.lbsalary_entry.get())
AttributeError: 'function' object has no attribute 'lbname_entry'

伙计们,我收到了这个错误。请帮助我,我也是python的新手,所以请用简单的语言解释一下。

标签: pythonmysqltkinter

解决方案


lbname_entry您可以将和的值传递lbsalary_entrysave_data()

def save_data(name, salary):
    query_insert = "INSERT INTO EMPLOYEE_DATA (NAME, SALARY) VALUES (%s, %s)"
    my_cursor.execute(query_insert, (name, salary))
    conn.commit()

然后修改command选项btn1

btn1 = tk.Button(newWindow, text='SAVE', command=lambda: save_data(lbname_entry.get(), lbsalary_entry.get()))

推荐阅读