Python在tkinter中显示输入的文本

2024-09-27 20:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个简单的Tkinter表格。它应该读取用户的输入,然后在单击按钮时显示结果

但是,我的代码没有返回任何内容。我发现了这个线索: Python Tkinter Entry get()

但我仍然没有返回用户输入的文本

这是我的剧本。感谢您的帮助:

import tkinter as tk
import tkinter.font as tkFont


class App:
    def __init__(self, root):
        # setting title
        root.title("undefined")
        # setting window size
        global result
        width = 600
        height = 500
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        LineEdit = tk.Entry(root)
        LineEdit["borderwidth"] = "2px"
        LineEdit.place(x=250, y=50, width=289, height=30)
        result = LineEdit.get()

        LineLabel = tk.Label(root)
        LineLabel["text"] = "Enter Your Input:"
        LineLabel.place(x=60, y=50, width=177, height=30)

        GoButton = tk.Button(root)
        GoButton["text"] = "Analyze"
        GoButton.place(x=170, y=130, width=195, height=58)
        GoButton["command"] = self.DisplayInput

    def DisplayInput(self):
        print(result)


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Tags: 用户selftkinterplacerootresultwidthtk
1条回答
网友
1楼 · 发布于 2024-09-27 20:20:35

您应该在DisplayInput()内获取LineEdit的内容。但是您需要将LineEdit更改为实例变量self.LineEdit,否则无法在DisplayInput()内访问它:

import tkinter as tk
import tkinter.font as tkFont


class App:
    def __init__(self, root):
        # setting title
        root.title("undefined")
        # setting window size
        #global result
        width = 600
        height = 500
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        self.LineEdit = tk.Entry(root)
        self.LineEdit["borderwidth"] = "2px"
        self.LineEdit.place(x=250, y=50, width=289, height=30)
        #result = LineEdit.get()

        LineLabel = tk.Label(root)
        LineLabel["text"] = "Enter Your Input:"
        LineLabel.place(x=60, y=50, width=177, height=30)

        GoButton = tk.Button(root)
        GoButton["text"] = "Analyze"
        GoButton.place(x=170, y=130, width=195, height=58)
        GoButton["command"] = self.DisplayInput

    def DisplayInput(self):
        result = self.LineEdit.get()
        print(result)


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

相关问题 更多 >

    热门问题