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

Python TKinter聊天界面窗口无法弹出,报AttributeError错误求助

问题描述

我用Tkinter和pyttsx3编写了聊天机器人界面代码,预期运行后弹出界面窗口,但实际运行时报错,错误信息如下:

Traceback (most recent call last): File "C:\AI Projects\ChatBot\app.py", line 78, in app.run() File "C:\AI Projects\ChatBot\app.py", line 16, in run self.window.mainloop() ^^^^^^^^^^^ AttributeError: 'ChatApplication' object has no attribute 'window'

附完整代码:

from tkinter import *

import pyttsx3
from chat import bot_name, get_response

engine = pyttsx3.init()
BG_GRAY = "#d4930b"
BG_COLOR = "#f2ece0"
TEXT_COLOR = "#000000"
FONT = "Helvetica 12"
FONT_BOLD = "Helvetica 11 bold"


class ChatApplication:
    def _init_(self):
        self.window = Tk()
        self._setup_main_window()

    def run(self):
        self.window.mainloop()

    def _setup_main_window(self):
        self.window.title("ChatBot")
        self.window.resizable(width=False, height=False)
        self.window.configure(width=750, height=600, bg=BG_GRAY)

        # head label
        head_label = Label(
            self.window,
            bg=BG_COLOR,
            fg=TEXT_COLOR,
            text="IIUC Admission Helpdesk",
            font=FONT_BOLD,
            pady=10,
        )

        head_label.place(relwidth=1)

        # tiny divider
        line = Label(self.window, width=450, bg=BG_GRAY)
        line.place(relwidth=1, rely=0.07, relheight=0.012)

        # text widget
        self.text_widget = Text(
            self.window, width=20, height=2, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, padx=5, pady=5
        )
        self.text_widget.place(relheight=0.745, relwidth=1, rely=0.08)
        self.text_widget.configure(cursor="arrow", state=DISABLED)

        # scroll bar
        scrollbar = Scrollbar(self.text_widget)
        scrollbar.place(relheight=1, relx=0.974)
        scrollbar.configure(command=self.text_widget.yview)

        # bottom label
        bottom_label = Label(self.window, bg=BG_GRAY, height=80)
        bottom_label.place(relwidth=1, rely=0.825)

        # message entry box
        self.msg_entry = Entry(bottom_label, bg="#dedfde", fg=TEXT_COLOR, font=FONT)
        self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
        self.msg_entry.focus()
        self.msg_entry.bind("<Return>", self._on_enter_pressed)

        # send button
        send_button = Button(
            bottom_label,
            text="Send",
            font=FONT_BOLD,
            width=20,
            bg=BG_GRAY,
            command=lambda: self._on_enter_pressed(None),
        )
        send_button.place(relx=0.77, rely=0.008, relheight=0.06, relwidth=0.22)

    def _on_enter_pressed(self, event):
        msg = self.msg_entry.get()
        self._insert_message(msg, "You")

    def _insert_message(self, msg, sender):
        if not msg:
            # return
            self.msg_entry.delete(0, END)
            msg1 = f"{sender}: {msg}\n\n"
            self.text_widget.configure(state=NORMAL)
            self.text_widget.insert(END, msg1)
            self.text_widget.configure(state=DISABLED)
            msg2 = f"{bot_name}: {get_response(msg)}\n\n"
            self.text_widget.configure(state=NORMAL)
            self.text_widget.insert(END, msg2)
            self.text_widget.configure(state=DISABLED)
            self.text_widget.see(END)

    # speak(msg2)


def speak(Response):
    engine.say(Response)
    engine.runAndWait()


app = ChatApplication()
app.run()

解决方案

1. 修复构造函数命名错误

报错核心原因是Python类的构造函数命名不符合规范:你写的是_init_(前后各一个下划线),但Python要求构造函数必须是__init__(前后各两个下划线)。因为构造函数未被正确调用,self.window属性从未初始化,调用run()方法时就会触发AttributeError。

修改ChatApplication类的构造函数:

def __init__(self):
    self.window = Tk()
    self._setup_main_window()

2. 修正消息插入逻辑

原代码中_insert_message方法在输入为空时仍会执行消息插入,导致空消息显示。调整逻辑,空输入时直接返回:

def _insert_message(self, msg, sender):
    if not msg:
        self.msg_entry.delete(0, END)
        return
    # 清空输入框
    self.msg_entry.delete(0, END)
    msg1 = f"{sender}: {msg}\n\n"
    self.text_widget.configure(state=NORMAL)
    self.text_widget.insert(END, msg1)
    self.text_widget.configure(state=DISABLED)
    msg2 = f"{bot_name}: {get_response(msg)}\n\n"
    self.text_widget.configure(state=NORMAL)
    self.text_widget.insert(END, msg2)
    self.text_widget.configure(state=DISABLED)
    self.text_widget.see(END)
    # 启用语音播报
    speak(msg2)

内容的提问来源于stack exchange,提问作者Tasmia Islam Ishika

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:53:13