python PySimpleGUIでInputTextの値をSliderに反映させる

python PySimpleGUIでInputTextの値をSliderに反映させる

pythonで、ライブラリPySimpleGUIを使用して、InputTextの値をSliderに反映させるサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

PySimpleGUIインストール

PySimpleGUIをインストールされていない方は、pipでインストールしておきます。

PySimpleGUI

<出力結果>
Collecting PySimpleGUI
  Downloading PySimpleGUI-4.41.2-py3-none-any.whl (348 kB)
     |████████████████████████████████| 348 kB 1.3 MB/s
Installing collected packages: PySimpleGUI
Successfully installed PySimpleGUI-4.41.2

Sliderに反映

Sliderに反映させるには、イベントを設定して、Sliderの値を更新します。

以下は、イベントを使用して、InputTextの値をSliderに反映させるサンプルコードとなります。

import PySimpleGUI as sg

# ウィンドウのテーマ
sg.theme('LightGreen')

# ウィンドウのレイアウト
layout = [
       [sg.Text('スライダー')],
       [sg.Slider(range=(0.0,100.0), default_value=0.0, resolution=1.0, orientation='h',key='sl1',enable_events=True)],
       [sg.InputText(default_text='0',size=(5,1), key='txt1'),sg.Button('Set',key='btn1')]
    ]

# ウィンドウオブジェクトの作成
window = sg.Window('title', layout, size=(300, 300))

# イベントのループ
while True:
    # イベントの読み込み
    event, values = window.read()
    # ウィンドウの×ボタンクリックで終了
    if event == sg.WIN_CLOSED:
        break
    elif event == 'btn1':
        window['sl1']. Update(values['txt1'])
# ウィンドウ終了処理
window.close()

実行結果

Sliderの値を、InputTextに反映させるには、以下のコードにSliderのイベントを追加します。

import PySimpleGUI as sg

# ウィンドウのテーマ
sg.theme('LightGreen')

# ウィンドウのレイアウト
layout = [
       [sg.Text('スライダー')],
       [sg.Slider(range=(0.0,100.0), default_value=0.0, resolution=1.0, orientation='h',key='sl1',enable_events=True)],
       [sg.InputText(default_text='0',size=(5,1), key='txt1'),sg.Button('Set',key='btn1')]
    ]

# ウィンドウオブジェクトの作成
window = sg.Window('title', layout, size=(300, 300))

# イベントのループ
while True:
    # イベントの読み込み
    event, values = window.read()
    # ウィンドウの×ボタンクリックで終了
    if event == sg.WIN_CLOSED:
        break
    elif event == 'sl1':
        window['txt1'].Update(values['sl1'])
    elif event == 'btn1':
        window['sl1']. Update(values['txt1'])
# ウィンドウ終了処理
window.close()

実行結果