目录

前言

一、Button Element

二、使用步骤

1.参数

2.参数说明

         3.常用参数使用

总结



前言

基于官方链接:Call reference - PySimpleGUI

一、Button Element

按钮元素 - 定义所有可能的按钮。 Submit、FileBrowse 等可创建快捷一个 Button。

二、使用步骤

1.参数

Button(button_text = "",
    button_type = 7,
    target = (None, None),
    tooltip = None,
    file_types = (('ALL Files', '*.* *'),),
    initial_folder = None,
    default_extension = "",
    disabled = False,
    change_submits = False,
    enable_events = False,
    image_filename = None,
    image_data = None,
    image_size = (None, None),
    image_subsample = None,
    border_width = None,
    size = (None, None),
    s = (None, None),
    auto_size_button = None,
    button_color = None,
    disabled_button_color = None,
    highlight_colors = None,
    mouseover_colors = (None, None),
    use_ttk_buttons = None,
    font = None,
    bind_return_key = False,
    focus = False,
    pad = None,
    p = None,
    key = None,
    k = None,
    right_click_menu = None,
    expand_x = False,
    expand_y = False,
    visible = True,
    metadata = None)

2.参数说明

TypeNameMeaning
strbutton_text

Text to be displayed on the button 

按钮上显示的文本

intbutton_type

You should NOT be setting this directly. ONLY the shortcut functions set this 

您不应该直接设置它。 只有快捷功能设置

str or (int, int)targetkey or (row,col) target for the button. Note that -1 for column means 1 element to the left of this one. The constant ThisRow is used to indicate the current row. The Button itself is a valid target for some types of button
strtooltip

text, that will appear when mouse hovers over the element

鼠标移动元素时显示的文本

Tuple[(str, str), ...]file_types

the filetypes that will be used to match files. To indicate all files: (("ALL Files", ". *"),). Note - NOT SUPPORTED ON MAC

支持的文件类型;

strinitial_folder

starting path for folders and files

文件或文件夹的初始路径或默认路径

strdefault_extensionIf no extension entered by user, add this to filename (only used in saveas dialogs)
(bool or str)disabled

If True button will be created disabled. If BUTTON_DISABLED_MEANS_IGNORE then the button will be ignored rather than disabled using tkinter

True-按钮被禁用

False-按钮启用,默认启用

boolchange_submits

DO NOT USE. Only listed for backwards compat - Use enable_events instead

不使用。 仅为向后兼容列出

使用 enable_events替代

boolenable_events

Turns on the element specific events. If this button is a target, should it generate an event when filled in

strimage_filename

image filename if there is a button image. GIFs and PNGs only.

图片作为一个按钮,只支持GIF,PNG格式

bytes or strimage_data

Raw or Base64 representation of the image to put on button. Choose either filename or data

Base64图片代码

(int, int)image_size

Size of the image in pixels (width, height)

图片大小;width:长; height:高度

intimage_subsample

amount to reduce the size of the image. Divides the size by this number. 2=1/2, 3=1/3, 4=1/4, etc

图片缩放比例;参数只能是int, 

例如设置为2,则图片会缩小到1/2的大小

intborder_width

width of border around button in pixels

按钮的边框

(int or None, int or None) or (None, None) or intsize

(w, h) w=characters-wide, h=rows-high. If an int instead of a tuple is supplied, then height is auto-set to 1

按钮的长度和高度

(int or None, int or None) or (None, None) or ints

Same as size parameter. It's an alias. If EITHER of them are set, then the one that's set will be used. If BOTH are set, size will be used

size的别名

boolauto_size_button

if True the button size is sized to fit the text

True-自动适应文本的大小

(str, str) or str or (int, int) or Nonebutton_color

Color of button. default is from theme or the window. Easy to remember which is which if you say "ON" between colors. "red" on "green". Normally a tuple, but can be a simplified-button-color-string "foreground on background". Can be a single color if want to set only the background.

按钮的背景色

如果是元组时,第一个参数为按钮字体颜色,第二个参数为按钮背景色

(str, str) or strdisabled_button_color

colors to use when button is disabled (text, background). Use None for a color if don't want to change. Only ttk buttons support both text and background colors. tk buttons only support changing text color

禁用按钮时使用的颜色(文本、背景)。 如果不想更改,请使用 None 作为颜色。 只有 ttk 按钮支持文本和背景颜色。 tk 按钮仅支持更改文本颜色

(str, str)highlight_colors

colors to use when button has focus (has focus, does not have focus). None will use colors based on theme. Only used by Linux and only for non-TTK button

按钮有焦点时使用的颜色(有焦点,没有焦点)。 设置为None时会使用基于主题的颜色。 仅支持 Linux系统下使用且仅用于非 TTK 按钮

(str, str) or strmouseover_colors

Important difference between Linux & Windows! Linux - Colors when mouse moved over button. Windows - colors when button is pressed. The default is to switch the text and background colors (an inverse effect)

Linux 和 Windows 之间的重要区别! Linux - 鼠标移到按钮上时的颜色。 Windows - 按下按钮时的颜色。 默认是切换文本和背景颜色(反效果)

booluse_ttk_buttons

True = use ttk buttons. False = do not use ttk buttons. None (Default) = use ttk buttons only if on a Mac and not with button images

True = 使用 ttk 按钮。 False = 不使用 ttk 按钮。 无(默认)= 仅在 Mac 上使用 ttk 按钮而不是按钮图像

(str or (str, int[, str]) or None)font

specifies the font family, size, etc. Tuple or Single string format 'name size styles'. Styles: italic * roman bold normal underline overstrike

设置字体大小

boolbind_return_key

If True the return key will cause this button to be pressed

如果为 True 则返回键将导致该按钮被按下

boolfocus

if True, initial focus will be put on this button

如果为 True,初始焦点将放在此按钮上

(int, int or (int, int),(int,int) or int,(int,int)) or ((int, int),int) or intpad

Amount of padding to put around element in pixels (left/right, top/bottom) or ((left, right), (top, bottom)) or an int. If an int, then it's converted into a tuple (int, int)

设置间距,参数对应(左,右),(上,下)也可以写成(左/右),(上/下)

(int, int or (int, int),(int,int) or int,(int,int)) or ((int, int),int) or intp

Same as pad parameter. It's an alias. If EITHER of them are set, then the one that's set will be used. If BOTH are set, pad will be used

pad的别名

str or int or tuple or objectkey

Used with window.find_element and with return values to uniquely identify this element to uniquely identify this element

标示唯一元素

str or int or tuple or objectk

Same as the Key. You can use either k or key. Which ever is set will be used.

key的别名

List[List[ List[str] or str ]]right_click_menu

A list of lists of Menu items to show when this element is right clicked. See user docs for exact format.

绑定右键事件,格式需为列表

boolexpand_x

If True the element will automatically expand in the X direction to fill available space

如果为 True 元素将自动在 X 方向扩展以填充可用空间

boolexpand_y

If True the element will automatically expand in the Y direction to fill available space

如果为 True 元素将自动在 Y 方向扩展以填充可用空间

boolvisible

set visibility state of the element

设置元素是否可见

True-可见,默认值

False-隐藏

Anymetadata

User metadata that can be set to ANYTHING

可以设置为 ANYTHING 的用户元数据

3.常用参数使用

GUI截图:

 代码如下:

# encoding:utf-8
import PySimpleGUI as sg

if __name__ == '__main__':

    layout = [
        [sg.Text('Button Element Example', font=('宋体', 24), size=(50, 1), justification='center')],
        [sg.Button(button_text="Start",        # 按钮显示文本
                   tooltip='开始',             # 鼠标滑到按钮时显示的文本
                   file_types=(('ALL Files', '*.* *'),),  # 支持的文件类型,打开文件时可以用到
                   border_width=2,             # 按钮边框
                   size=(10, 1),              # 按钮的长度,高度
                   auto_size_button=True,      # 自否自适应
                   button_color=('white', 'green'),  # 按钮字体颜色, 按钮的背景色
                   font=('宋体', 18),        # 设置字体,大小
                   bind_return_key=False,    # 是否绑定按键
                   focus=True,              # 鼠标是否放置在此按钮上
                   pad=((300, 0), (20, 0)),    # 设置元素的间距 (左,右),(上,下)
                   key='START-EXEC',       # 元素唯一标示
                   visible=True)]         # 元素是否可见
    ]

    window = sg.Window('按钮元素示例', layout)

    while True:  # Event Loop
        event, values = window.read(timeout=1000)

        if event in (None, 'Exit'):
            break

    window.close()

4.bind 绑定事件

用于将 tkinter 事件添加到元素。 tkinter 特定数据在 Element 的成员变量 user_bind_event 中

bind(bind_string, key_modifier)

TypeNameMeaning
strbind_string

The string tkinter expected in its bind function

 tkinter 在其绑定函数中预期的字符串

strkey_modifier

Additional data to be added to the element's key when event is returned

返回事件时要添加到元素键的附加数据

window['START-EXEC'].bind("<Return>", '-Return-Key')  # 绑定回车事件

<Return>   对应回车键

-Return-Key  对应返回事件时增加的字符数据

代码如下:

# encoding:utf-8
import PySimpleGUI as sg

if __name__ == '__main__':

    layout = [
        [sg.Text('Button Element Example', font=('宋体', 24), size=(50, 1), justification='center')],
        [sg.Button(button_text="Start",        # 按钮显示文本
                   tooltip='开始',             # 鼠标滑到按钮时显示的文本
                   file_types=(('ALL Files', '*.* *'),),  # 支持的文件类型,打开文件时可以用到
                   border_width=2,             # 按钮边框
                   size=(10, 1),              # 按钮的长度,高度
                   auto_size_button=True,      # 自否自适应
                   button_color=('white', 'green'),  # 按钮字体颜色, 按钮的背景色
                   font=('宋体', 18),        # 设置字体,大小
                   bind_return_key=False,    # 是否绑定按键
                   focus=True,              # 鼠标是否放置在此按钮上
                   pad=((300, 0), (20, 0)),    # 设置元素的间距 (左,右),(上,下)
                   key='START-EXEC',       # 元素唯一标示
                   visible=True)]         # 元素是否可见
    ]

    window = sg.Window('按钮元素示例', layout, finalize=True)

    while True:  # Event Loop
        event, values = window.read(timeout=1000)
        window['START-EXEC'].bind("<Return>", '-Return-Key')  # 绑定回车事件

        if event in (None, 'Exit'):
            break

        if event == 'START-EXEC-Return-Key':  # 按回车键时返回的事件
            print('绑定回车')

    window.close()

总结

以上就是今天要讲的内容,本文仅仅简单介绍了PySimpleGUI Button元素的使用,个别参数可能描述不太准确,请各位大佬纠正,谢谢!

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐