You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python tkinter应用报错NameError: name 'nume_tehnician'未定义求助

Tkinter SQLite应用NameError问题解决办法

问题重现

运行代码时触发如下错误:

Traceback (most recent call last):
  File "C:\Users\sucimi2\PycharmProjects\pythonProject3\main.py", line 61, in <module>
    data_insert_tuple = (nume_tehnician, schimb, linia,
NameError: name 'nume_tehnician' is not defined

错误原因

  1. 作用域错位:数据库插入逻辑被写在全局代码中,但nume_tehnician等变量是在trimitere_date函数内部定义的,全局作用域无法访问这些变量;同时GUI组件的创建代码错误放入函数内部,导致组件仅在点击按钮后才生成,违背GUI初始化逻辑。
  2. SQL语句错误:INSERT语句的VALUES部分写了7个?占位符,但表只有6个字段,对应值只需6个,多写了一个占位符。
  3. 拼写错误:descriere_problmea应为descriere_problema,字母缺失导致变量未定义。
  4. 缩进混乱:Python对缩进要求严格,代码中if/else、函数内代码缩进不规范,导致逻辑结构错位。
  5. 冗余代码:重复编写清空输入框的代码,且位置错误。

修正后的完整代码

import tkinter
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import sqlite3

# CREEAREA APLICATIEI + CONFIGURAREA ACESTEIA
root = tk.Tk()
root.title("Raport 1.0d")

frame = tk.Frame(root)
frame.pack()

# CREEAREA FRAME-URILOR SI COMPONENTELOR GUI (全局作用域初始化时创建)
info_frame = tk.LabelFrame(frame, text="Informatii USER/probleme")
info_frame.grid(row=0, column=0, padx=20, pady=20)

# CREEARE VARIABILELOR GUI
nume_tehnician_label = tk.Label(info_frame, text="Numele tehnician")
nume_tehnician_dropdown = ttk.Combobox(info_frame, values=["nume1", "nume2", "nume3"])
nume_tehnician_label.grid(row=0, column=0)
nume_tehnician_dropdown.grid(row=1, column=0)

schimb_label = tk.Label(info_frame, text="Schimbul")
schimb_dropdown = ttk.Combobox(info_frame, values=["1", "2", "3"])
schimb_label.grid(row=0, column=1)
schimb_dropdown.grid(row=1, column=1)

linia_label = tk.Label(info_frame, text="Linia")
linia_dropdown = ttk.Combobox(info_frame, values=["LINIA1", "LINIA2", "LINIA3"])
linia_label.grid(row=0, column=2)
linia_dropdown.grid(row=1, column=2)

descriere_problema_label = tk.Label(info_frame, text="Descrierea problemei")
descriere_problema_label.grid(row=2, column=0)
descriere_problema_entry = tk.Entry(info_frame)
descriere_problema_entry.grid(row=3, column=0)

durata_interventie_label = tk.Label(info_frame, text="Durata interventiei (in minute)")
durata_interventie_label.grid(row=2, column=1)
durata_interventie_entry = tk.Entry(info_frame)
durata_interventie_entry.grid(row=3, column=1)

rezolvare_problema_label = tk.Label(info_frame, text="Cum s-a rezolvat problema")
rezolvare_problema_label.grid(row=2, column=2)
rezolvare_problema_entry = tk.Entry(info_frame)
rezolvare_problema_entry.grid(row=3, column=2)

breakdown_checkbox = tk.Checkbutton(info_frame, text="BREAKDOWN (se bifeaza daca a fost BREAKDOWN)")
breakdown_checkbox.grid(row=4, column=1)

# ARANJAMENTUL PE APLICATIE
for widget in info_frame.winfo_children():
    widget.grid_configure(padx=10, pady=10)

# FUNCTIONALITATE BUTON_TRIMITERE
def trimitere_date():
    nume_tehnician = nume_tehnician_dropdown.get()
    schimb = schimb_dropdown.get()
    linia = linia_dropdown.get()
    descriere_problema = descriere_problema_entry.get()
    durata_interventie = durata_interventie_entry.get()
    rezolvare_problema = rezolvare_problema_entry.get()

    if not all([nume_tehnician, schimb, linia, descriere_problema, durata_interventie, rezolvare_problema]):
        messagebox.showerror("Eroare", "Completati toate campurile!")
        return

    messagebox.showinfo("Succes", "Datele au fost introduse cu succes!")
    print("Nume tehnician: " + nume_tehnician)

    # INSERARE DATE IN BAZA DE DATE
    conn = sqlite3.connect('raport_zilnic.db')
    tabel = '''CREATE TABLE IF NOT EXISTS raport_data
        (Nume_tehnician TEXT, Schimb TEXT, Linia TEXT,
            Descriere_problema TEXT, Durata_interventie TEXT,
            Rezolvare_problema TEXT)
        '''
    conn.execute(tabel)

    # 修正SQL占位符数量与字段一致
    data_insert_query = '''INSERT INTO raport_data (Nume_tehnician, Schimb, Linia, Descriere_problema, Durata_interventie, Rezolvare_problema) 
        VALUES (?, ?, ?, ?, ?, ?)'''
    # 修正拼写错误
    data_insert_tuple = (nume_tehnician, schimb, linia,
                        descriere_problema, durata_interventie, rezolvare_problema )
    cursor = conn.cursor()
    cursor.execute(data_insert_query, data_insert_tuple)
    conn.commit()
    conn.close()

    # GOLESTE INPUT-URILE DUPA TRIMITERE
    descriere_problema_entry.delete(0, tk.END)
    durata_interventie_entry.delete(0, tk.END)
    rezolvare_problema_entry.delete(0, tk.END)

# BUTOANELE
buton_trimitere = tkinter.Button(info_frame, text="Trimitere", fg="blue", command=trimitere_date)
buton_trimitere.grid(row=5, column=1, sticky="news")

buton_iesire = tkinter.Button(info_frame, fg="red", text="Iesire", command=root.quit)
buton_iesire.grid(row=6, column=1, sticky="news")

# AFISAREA APLICATIEI
root.mainloop()

关键修正点说明

  • 将GUI组件创建代码移到全局作用域,确保程序启动时生成所有界面元素。
  • 数据库插入逻辑完全放入trimitere_date函数内部,确保能访问函数内定义的变量。
  • 修正SQL插入语句的占位符数量,与表字段数保持一致。
  • 修复变量名拼写错误。
  • 规范所有代码缩进,确保Python能正确识别代码块结构。
  • 移除冗余的清空输入框代码,仅在函数内执行一次。

内容的提问来源于stack exchange,提问作者Spravil Carina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:59:55