如何在GUI python中显示print()的输出

时间:2017-08-09 08:06:48

标签: python user-interface tkinter

我是创建GUI的新手。我正在使用Tkinter在Python中完成它。在我的程序中,我计算了以下特征

def my_myfunction():
    my code ...
    print("Centroid:", centroid_x, centroid_y)
    print("Area:", area)
    print("Angle:", angle)

我想请求任何帮助/提示如何在GUI窗口中显示这些值或如何将它们保存在.txt文件中,以便我可以在我的GUI中调用它们 提前致谢

2 个答案:

答案 0 :(得分:0)

有几种方法可以在tkiner中显示任何操作的结果。

您可以使用LabelEntryText,甚至弹出消息框。还有其他一些选择,但这些可能就是你想要的。

看一下下面的例子。

我有一个简单的添加程序,需要2个数字并将它们加在一起。它将在每种字段中显示结果,您可以将其用作tkinter中的输出。

import tkinter as tk
from tkinter import messagebox

class App(tk.Frame):

    def __init__(self, master):
        self.master = master

        lbl1 = tk.Label(self.master, text = "Enter 2 numbers to be added \ntogether and click submit")
        lbl1.grid(row = 0, column = 0, columnspan = 3)

        self.entry1 = tk.Entry(self.master, width = 5)
        self.entry1.grid(row = 1, column = 0)

        self.lbl2 = tk.Label(self.master, text = "+")
        self.lbl2.grid(row = 1, column = 1)

        self.entry2 = tk.Entry(self.master, width = 5)
        self.entry2.grid(row = 1, column = 2)

        btn1 = tk.Button(self.master, text = "Submit", command = self.add_numbers)
        btn1.grid(row = 2, column = 1)

        self.lbl3 = tk.Label(self.master, text = "Sum = ")
        self.lbl3.grid(row = 3, column = 1)

        self.entry3 = tk.Entry(self.master, width = 10)
        self.entry3.grid(row = 4, column = 1)

        self.text1 = tk.Text(self.master, height = 1, width = 10)
        self.text1.grid(row = 5, column = 1)

    def add_numbers(self):

        x = self.entry1.get()
        y = self.entry2.get()

        if x != "" and y != "":
            sumxy = int(x) + int(y)

            self.lbl3.config(text = "Sum = {}".format(sumxy))

            self.entry3.delete(0, "end")
            self.entry3.insert(0, sumxy)

            self.text1.delete(1.0, "end")
            self.text1.insert(1.0, sumxy)

            messagebox.showinfo("Sum of {} and {}".format(x,y), 
                                "Sum of {} and {} = {}".format(x, y, sumxy))


if __name__ == "__main__":

    root = tk.Tk()
    myapp = App(root)
    root.mainloop()

答案 1 :(得分:-1)

Tkinter很简单,也是一种简单的GUI方式,但有时它可能令人沮丧。但是你之前应该阅读过这些文档。 但是,你可以这样做。

from tkinter import *

yourData = "My text here"

root = Tk()
frame = Frame(root, width=100, height=100)
frame.pack()

lab = Label(frame,text=yourData)
lab.pack()

root.mainloop()