【问题标题】:How can I pass the output from each of the print statements into tkinter?如何将每个打印语句的输出传递到 tkinter?
【发布时间】:2020-06-30 16:20:37
【问题描述】:
# Create a class DataExplore
class DataExplore:

    # Define initialization method
    def __init__(self, filepath):
        self.filepath = filepath
        self.data = pd.read_csv(filepath)

        
    # Define desc_stats method, with argument
    def desc_stats(self):
        # Return a description data_as_csv
        return self.data.describe()
    
    def miss_values(self):
        return self.data.isnull().sum().sum() 
    
    def fill_missing(self):
        fill = self.data.interpolate(method='linear', axis=0).ffill().bfill()
        return fill
    
    def correl(self):
        return self.data.corr(method = 'pearson')
    
    ### linear regression
    def ln_reg(self):
        self.data = self.data.interpolate(method='linear', axis=0).ffill().bfill()
        x = self.data.iloc[:, 2:]
        y = self.data.iloc[:,1]
        model = sm.OLS(y, x).fit()
        return model.summary()

## Passed the cvs file to the class DataExplore
data_explore = DataExplore('project_data.csv')

#print(data_explore.desc_stats())

#print (data_explore.correl())

#print(data_explore.miss_values())

#print(data_explore.fill_missing())

print(data_explore.ln_reg())

【问题讨论】:

  • 您的示例中没有 tkinter 代码。 “进入 tkinter”是什么意思?

标签: python python-3.x tkinter tkinter-canvas


【解决方案1】:

您可以使用上下文管理器 redirect_stdout 将打印输出重定向到数据结构。
然后将数据结构的内容显示到一个 tkinter 窗口:

from contextlib import redirect_stdout
import tkinter as tk


class Txt:

    def __init__(self):
        self._data = []

    def write(self, val):
        self._data.append(str(val))

    def __str__(self):
        return ''.join(self._data)


if __name__ == '__main__':

    txt = Txt()

    with redirect_stdout(txt):
        print('this text')
        print('is being redirected')
        print('to a Txt object')
        print('than displayed in a tkinter window')

    print('this goes to the console')

    root = tk.Tk()
    text_w = tk.Text(root)
    text_w.insert('1.0', str(txt))
    text_w.pack(expand=True, fill=tk.BOTH)

    root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多