【问题标题】:How to have PySimpleGUI default text in Output on window opening如何在打开窗口时在输出中显示 PySimpleGUI 默认文本
【发布时间】:2021-07-18 06:35:32
【问题描述】:

我正在使用PySimpleGUI 创建一个文本输出框。

在打开程序时,我希望输出在按下任何按钮之前显示一些默认文本。

我怎样才能让这种情况发生? window.Read() 等待按下按钮。 window.refresh() 似乎不会将文本强制显示在窗口中。

import PySimpleGUI as sg

initialString = "I want this text to display on window opening."

def gui2():
    layout = [
              [sg.Output(size=(90,20), background_color='black', text_color='white')],
              [sg.Button('Do things'), sg.Button('Exit')]
             ]
    
    window = sg.Window("Funny Title", layout)
    
    #window.read()  #I need to press a button before the text will display
    #window.refresh() #doesn't refresh the output
    print(initialString)
    #window.refresh() #doesn't refresh the output
    
    while True:
        event, values = window.read() 
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        elif event == 'Do things':
            print("You pressed the button")
    window.close() 
gui2()

【问题讨论】:

    标签: python user-interface pysimplegui


    【解决方案1】:

    当然,答案是在我发帖 5 分钟后找到的。

    window = sg.Window("Funny Title", layout, finalize = True)
    

    这修复了窗口,随后的 print 语句将根据需要出现在输出中。

    .

    编辑: 从下面的评论中,我还将布局从 sg.Outline 更改为 sg.Multiline:

                  sg.Multiline(size=(90,20), 
                               background_color='black', 
                               text_color='white', 
                               reroute_stdout=True, 
                               reroute_stderr=True,
                               autoscroll = True)],
    

    【讨论】:

    • Multiline 元素已经做了很多工作,现在推荐用于标准输出打印。看一下多行的调用参考,你会发现很多关于标准输出的控件。例如,您可以路由到窗口和控制台等。
    • 很多。我已经改过了。
    • 我想添加更多细节:“finalize = True”选项允许您在进入主“while True”事件循环之前读取和更新窗口中元素的值。因此,它允许您将这个额外的代码(操作元素)放在“window =”声明和“while True”事件循环之间。
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2022-06-25
    相关资源
    最近更新 更多