Skip to main content
 首页 » 编程设计

python之Tkinter 按钮向消息添加行

2025年05月04日16Free-Thinker

我正在尝试使用 tkinter 在 python 中制作一个简单的 gui 应用程序。有一个消息字段、一个条目和一个按钮。我正在尝试为将条目中的文本发送到消息字段然后清除条目的按钮编写命令。这是我的代码:

from tkinter import * 
from tkinter.ttk import * 
 
class window(Frame): 
 
    def __init__(self, parent): 
        messageStr="Hello and welcome to my incredible chat program its so awesome" 
 
        Frame.__init__(self, parent) 
 
        self.parent = parent 
 
        self.parent.title("Hello World") 
        self.style = Style() 
        self.style.theme_use("default") 
 
        self.pack(fill=BOTH, expand="yes") 
 
        lfone = Frame(self) 
        lfone.pack(fill=BOTH, expand="yes") 
 
 
        myentry = Entry(self).pack(side=LEFT, fill=BOTH, expand="yes", padx=5) 
 
        messager = Message(lfone, text=messageStr, anchor=S+W, justify=LEFT).pack(fill=BOTH, expand="yes", padx=5, pady=5) 
 
        sendbutton = Button(self, text="Send", command=self.sendbuttoncommand).pack(side=RIGHT) 
 
    def sendbuttoncommand(*args): 
        messager.text = messager.text + myentry.get() 
        myentry.delete(first, last=None) 
 
 
def main(): 
 
    root = Tk() 
    root.geometry("300x200+300+300") 
    app=window(root) 
    root.mainloop() 
 
if __name__ == '__main__': 
    main() 

我尝试了 sendbuttoncommand 的几种变体,包括将其嵌套在 def init 中,以及将 messager 和我的条目更改为 self.messager/myentry,但都没有成功。就目前而言,当我尝试运行它时,我在 messager 上收到了一个名称错误。如何影响方法范围之外的变量?我希望避免在这种情况下使用全局变量。

请您参考如下方法:

在你的sendbuttoncommand方法,messager未定义,因为它仅在 __init__ 中本地定义.这就是导致 NameError 的原因。

如果要重复使用messager在sendbuttoncommand方法,通过将其定义为 self.messager 使其成为实例的参数在你的__init__通过调用 self.messager 的方法在sendbuttoncommand .

但是,我怀疑您之后会遇到其他错误。