如何从tkinter文本部件中获取输入,当它在一个函数中时。

问题描述 投票:1回答:1

我是一个比较新的编码者,目前我在玩python中的tkinter,我在一个函数中使用一个文本部件,想把文本框的输入发送到另一个函数中。我的全局变量显示在模块级未定义,那么如果它在一个函数中,我怎么能让它在模块级定义呢?

当我按下发送邮件按钮时,我得到了这个错误信息 "NameError: name 'user_message_entry' is not defined"

有什么建议吗?非常感谢!

最低限度的复制。

import tkinter as tk

root = tk.Tk()
root.geometry("500x500")


def send_email():
    global user_message_entry
    subject = ":)"
    body = user_message_entry.get("1.0", "end")
    message = f"subject: {subject}\n\n {body}"
    print(message)


def feedback():
    feedback_window = tk.Toplevel()
    feedback_window.geometry("690x650")

    message_frame = tk.Frame(feedback_window)
    message_frame.grid(row=0, column=0, columnspan=3)
    user_message_entry = tk.Text(message_frame, height=10, width=60)
    user_message_entry.grid(row=0, column=0)

    send_email_button = tk.Button(feedback_window, command=send_email,
                                  height=20, width=20, bg="yellow", text="send email")
    send_email_button.grid(row=1, column=0)


open_feedback_button = tk.Button(root, command=feedback, height=20, width=20, bg="yellow", text="open feedback window")
open_feedback_button.grid(row=1, column=0)

root.mainloop()
python python-3.x tkinter global-variables tkinter-text
1个回答
0
投票

你可以用Object orient方法论来做访问sympler,另一个选择也可以用globals()来做变量的全局性

一种方式

globals()['user_message_entry'] = tk.Text(message_frame, height=10, width=60)

.... 

而在另一个函数中,你可以调用

body = globals()['user_message_entry'].get("1.0", "end")

第二种方式

面向对象的程序设计对每一种类型的问题解决都有好处,所以你也可以使用类

import tkinter as tk

class CBased:
    def __init__(self, master, *args, **kwargs):
        super(CBased, self).__init__(*args, *kwargs)
        self.master = master
        master.geometry("500x500")

        self.open_feedback_button = tk.Button(master, command=self.feedback, height=20, width=20, bg="yellow", text="open feedback window")
        self.open_feedback_button.grid(row=1, column=0)

    def send_email(self):
        subject = ":)"
        body = self.user_message_entry.get("1.0", "end")
        message = f"subject: {subject}\n\n {body}"
        print(message)


    def feedback(self):
        self.feedback_window = tk.Toplevel()
        self.feedback_window.geometry("690x650")

        self.message_frame = tk.Frame(self.feedback_window)
        self.message_frame.grid(row=0, column=0, columnspan=3)
        self.user_message_entry = tk.Text(self.message_frame, height=10, width=60)
        self.user_message_entry.grid(row=0, column=0)

        self.send_email_button = tk.Button(self.feedback_window, command=send_email,
                                  height=20, width=20, bg="yellow", text="send email")
        self.send_email_button.grid(row=1, column=0)

def main():
    root        = Tk()
    myobj       = CBased(root)
    root.mainloop()

if __name__ == "__main__":main()

这样一来,你就可以用self.xyz来调用每一个单项。

© www.soinside.com 2019 - 2024. All rights reserved.