简体   繁体   English

如何使用tkinter显示函数调用的输出?

[英]How do you use tkinter to display the output of a function call?

I'm trying to use using tkinter to demonstrate the functionality of a given python library. 我正在尝试使用tkinter来演示给定python库的功能。 The GUI must take textual input from the user, await a button push, send the input to the function, display the result, and repeat this process every time the user pushes the button. GUI必须从用户获取文本输入,等待按钮按下,将输入发送到函数,显示结果,并在每次用户按下按钮时重复此过程。

import tkinter as tk


def do_something(phrase):
    return phrase + phrase


def main():
    root = tk.Tk()
    root.title("Demo")

    tk.Label(root, text="Please enter a sentence: ").grid(row=0)
    user_input = tk.Entry(root)
    user_input.grid(row=0, column=1)
    result = tk.Button(root, text='Do something', command=do_something(user_input.get())).grid(row=1, column=1, sticky=tk.W, pady=4)
    tk.Label(root, text=result).grid(row=2, column=1)

    root.mainloop()


if __name__ == "__main__":
    main()

I don't know how to access the value returned by do_something() . 我不知道如何访问do_something()返回的值。 I imagine that once I understand how to do that, there might be the issue of ensuring that the process can be repeated as many times as the window remains open and the user presses the button. 我想,一旦我理解了如何做到这一点,可能会出现这样的问题:确保在窗口保持打开状态并且用户按下按钮时,该过程可以重复多次。

Guess that you want to set the text of the last label based on the input value of user_input . 猜测您要根据user_input的输入值设置最后一个标签的文本。 You can do it as below: 你可以这样做:

import tkinter as tk

def do_something(phrase):
    return phrase + phrase

def main():
    root = tk.Tk()
    root.title("Demo")

    tk.Label(root, text="Please enter a sentence: ").grid(row=0)
    user_input = tk.Entry(root)
    user_input.grid(row=0, column=1)
    result = tk.Label(root, text='')
    result.grid(row=2, column=0, columnspan=2)
    btn = tk.Button(root, text='Do something')
    btn.config(command=lambda: result.config(text=do_something(user_input.get())))
    btn.grid(row=1, column=1, sticky=tk.W, pady=4)

    root.mainloop()

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM