Pysimplegui 简明教程

PySimpleGUI - Popup Windows

PySimpleGUI 模块中以弹出窗口*前缀开头的函数会生成具有预定义外观的窗口。弹出窗口函数的名称表示其目的是否在其中提供按钮的配置。这些弹出窗口仅使用一行代码创建。每个弹出窗口都有特定的目的,然后立即关闭。

A function in PySimpleGUI module that start with the prefix popup* generates window of a predefined appearance. The name of the popup function indicates is purpose and configuration of buttons present on it. These popups are created with just one line of code. Each popup serves a certain purpose, and then closes immediately.

popup() 函数创建了一个最基本的弹出窗口。它可以像 print() 函数一样使用,在窗口上显示多个参数和一个“确定”按钮。它就像一个消息框,按“确定”按钮后立即消失

A most basic popup is created by the *popup()*function. It can be used like a print() function to display more than one parameters on the window, and an OK button. It acts like a message box, that disappears immediately on pressing the OK button

>>> import PySimpleGUI as psg
>>> psg.popup("Hello World")

它显示一个带有 Hello World 文本和“确定”按钮的弹出窗口。请注意,可以显示多个字符串。提供具有不同按钮配置的以下弹出窗口 −

It displays a popup window with Hello World text and OK button. Note that more than one strings can be displayed. Following popups with different button configurations are available −

  1. popup_ok − Display Popup with OK button only

  2. popup_ok_cancel − Display popup with OK and Cancel buttons

  3. popup_cancel − Display Popup with "cancelled" button text

  4. popup_yes_no − Display Popup with Yes and No buttons

  5. popup_error − Popup with colored button and 'Error' as button text

这些函数返回用户按下的按钮的文本。例如,如果用户按下确定取消弹出窗口的“确定”按钮,它将返回“确定”,这可以在进一步的编程逻辑中使用。

These functions return the text of the button pressed by the user. For example, if the user presses OK button of the ok-cancel popup, it returns Ok which can be used in further programming logic.

以下弹出窗口以文本形式接受用户输入,或允许用户从选择器中选择文件/文件夹/日期。

Following popups accept input from the user in the form of text or let the user select file/folder/date from the selectors.

  1. popup_get_text − Display Popup with text entry field. Returns the text entered or None if closed / cancelled

  2. popup_get_file − Display popup window with text entry field and browse button so that a file can be chosen by user.

  3. popup_get_folder − Display popup with text entry field and browse button so that a folder can be chosen.

  4. popup_get_date − Display a calendar window, get the user’s choice, return as a tuple (mon, day, year)

当用户完成选择并按下确定按钮时,弹出窗口的返回值为文本,可以在程序中进一步使用。

When user has made the selection and Ok button is pressed, the return value of the popup is the text, which can be used further in the program.

以下脚本显示了如何使用上述一些弹出窗口 −

Following script shows the use of some of the above popups −

import PySimpleGUI as psg
text = psg.popup_get_text('Enter your name', title="Textbox")
print ("You entered: ", text)
file=psg.popup_get_file('Select a file',  title="File selector")
print ("File selected", file)
folder=psg.popup_get_folder('Get folder', title="Folder selector")
print ("Folder selected",folder)
ch = psg.popup_yes_no("Do you want to Continue?",  title="YesNo")
print ("You clicked", ch)
ch = psg.popup_ok_cancel("Press Ok to proceed", "Press cancel to stop",  title="OkCancel")
if ch=="OK":
   print ("You pressed OK")
if ch=="Cancel":
   print ("You pressed Cancel")
psg.popup_no_buttons('You pressed', ch, non_blocking=True)
psg.popup_auto_close('This window will Autoclose')

Output − 下面显示了上述代码生成的弹出窗口 −

Output − The popups generated by the above code are shown below −

pop windows

Python console 上显示以下 output

The following output is displayed on the Python console

You entered: Tutorialspoint
File selected F:/python36/hello.png
Folder selected F:/python36/Scripts
You clicked Yes
You pressed Cancel

所有类型弹出窗口都是继承自弹出窗口类的各个类的对象。它们都具有相同的一组属性。这些属性具有特定的默认值,并可用于自定义弹出窗口对象的外观和行为。下表列出了通用参数 −

All types of popups are objects of respective classes inherited from popup class. All of them have a common set of properties. These properties have a certain default value, and can be used to customize the appearance and behaviour of the popup objects. Following table lists the common parameters −

Type

Parameter

Description

Any

*args

Values to be displayed on the popup

Str

title

Optional title for the window.

(str, str) or None

button_color

Color of the buttons shown (text color, button color)

Str

background_color

Window’s background color

Str

text_color

text color

Bool

auto_close

If True the window will automatically close

Int

auto_close_duration

time in seconds to keep window open before closing it automatically

Bool

non_blocking

If True then will immediately return from the function without waiting for the user’s input.

Tuple[font_name, size, modifiers]

font

specifies the font family, size, etc. Tuple or Single string format 'name size styles'.

Bool

grab_anywhere

If True can grab anywhere to move the window.

(int, int)

Location

Location on screen to display the top left corner of window. Defaults to window centered on screen

Bool

keep_on_top

If True the window will remain above all current windows

Bool

modal

If True, then makes the popup will behave like a Modal window. Default = True

Scrolled Popup

popup_scrolled() 函数生成一个弹出窗口,其中包含一个可滚动的文本框。使用此文本框可以显示大量文本,其中包含很多行的文本,这些行的字符数多于宽度。

The popup_scrolled() function generates a popup with a scrollable text box in it. Use this to display a large amount of text, consisting of many lines with number of characters more than the width.

size 属性是一个元组 (w, h),“w”表示一行中的字符数,“h”表示一次显示的行数。如果字符数/文本行数多于“w”或“h”,文本框的水平/垂直滚动条将激活。

The size property is a tuple (w, h) with "w" being the number of characters in one line, and "h" being the lines displayed at a time. The horizontal/vertical scrollbar to the text box will become active if the number of characters/no of lines of text are more than "w" or "h".

在以下示例中,一个大文件 zen.txt 显示在带有可滚动文本框的弹出窗口中。该文件包含 Python 的设计原则,称为“Python 之禅”。

In the following example, a big file zen.txt is displayed in a popup with scrollable text box. The file contains the design principles of Python called the "Zen of Python".

import PySimpleGUI as psg
file=open("zen.txt")
text=file.read()
psg.popup_scrolled(text, title="Scrolled Popup", font=("Arial Bold", 16), size=(50,10))

它将生成以下 output

It will produce the following output

scrolled popup

Progress Meter

“one_line_progress_meter”是一个弹出窗口,用于显示正在进行的长进程的直观表示,例如循环。它显示某个参数的瞬时值、完成进程的估计时间和已用时间。

The "one_line_progress_meter" is a popup that displays the visual representation of an ongoing long process, such as a loop. It shows the instantaneous value of a certain parameter, estimated time to complete the process, and the elapsed time.

在以下示例中,一个文本文件逐个字符进行读取。进度指示器以进度条的形式显示进程的进度、完成所需估计时间和计数的瞬时值。

In the following example, a text file is read character by character. The Progress meter shows the progress of the process in the form of a progress bar, estimated time required for completion, and the instantaneous value of the count.

import PySimpleGUI as psg
import os
size = os.path.getsize('zen.txt')
file=open("zen.txt")
i=0
while True:
   text=file.read(1)
   i=i+1
   if text=="":
      file.close()
      break
   print (text,end='')
   psg.one_line_progress_meter(
      'Progress Meter', i, size,
      'Character Counter'
   )

它将生成以下 output 窗口 −

It will produce the following output window −

progress meter

Debug Popup

在程序运行期间,通常需要跟踪某些变量的中间值,虽然后续的输出中不需要这些值。可以使用 PySimpleGUI 库中的 Print() 函数来实现此目的。

During the execution of a program, it is usually required to keep track of intermediate values of certain variables, although not required in the following output. This can be achieved by the Print() function in PySimpleGUI library.

Note − 与 Python 的内置 print() 函数不同,此函数中的“P”为大写。

Note − Unlike Python’s built-in print() function, this function has "P" in uppercase).

当程序第一次遇到此函数时,将显示调试窗口并在其中回显后续的所有打印内容。此外,我们可以使用 EasyPrinteprint ,它们也具有相同的效果。

As the program encounters this function for the first time, the debug window appears and all the subsequent Prints are echoed in it. Moreover, we can use EasyPrint or eprint that also have same effect.

以下程序计算用户输入数字的阶乘值。在 for 循环内,我们希望跟踪每次迭代中 f(阶乘)的值。这是通过 Print 函数完成的,并在调试窗口中显示。

The following program computes the factorial value of the number input by the user. Inside the for loop, we want to keep track of the values of f (for factorial) on each iteration. That is done by the Print function and displayed in the debug window.

import PySimpleGUI as psg
f=1
num=int(psg.popup_get_text("enter a number: "))
for x in range(1, num+1):
   f=f*x
   psg.Print (f,x)
print ("factorial of {} = {}".format(x,f))

假设用户输入 5,调试窗口会显示以下 output

Assuming that the user inputs 5, the debug window shows the following output

debug window