PySimpleGUI

PySimpleGUI code作成のヒント 10/17/2023

大分追加したので全編取り替えます。

# Python本家のホームページ ecookbook	
		*ChatGPT login tak@, opex 8/5/2024
	# Pythonのinstall youtube 説明
		
#部品の基本動作の詳細解説 wedgetと言う https://qiita.com/sunameri22/items/da002d628d7a28cd6e97 # RGBカラーをスライドバーで表示させる https://www.lab-nemoto.jp/www/leaflet_edu/else/ColorMaker.html # windowの色合い sg.theme('Kayak') # PySimpleGUIのinstall pip install PySimpleGUI PIL-->Pillowとしてinstallする # PySimpleGUIの動作不良発生の場合 ーー>Window11を入れ替えてやっと消えた  pip uninstall PySimpleGUI : まず不良をuninstallする  pip install PySimpleGUI==4.19.0 : 必要なverをinstallする. # try~exceptでエラー対応する while True: try: event, values = window.read() if event in (None, '-quit-'): break if event == '-file-': # your existing code for handling file selection except Exception as e: sg.popup_error(f"An error occurred: {e}") break # ボタンの動的作成(layoutへ作成する) [sg.Button(name) for name in url_link.keys() ], layout = [[sg.Text('test', text_color='Blue', background_color='White', font=('Arial',20))]] # ボタン位置・色を決める # 左、中央、右への配置はsg.Push()が便利  * 位置 left=100、right=10、top=50、bottom=50  [sg.Button('Button', pad=((left,right),(top,bottom)) )] [sg.Button('Button', pad=(left,right))]<--windowの横が広がる。 not so good. [sg.Button('End', pad=((150, 0),(50,0)))] # pad:Endボタンの配置設定 OK [sg.Button('Button', button_color=('blue','red'))] # sg.InputTextにフォーカスをセットする  window['-INPUT-'].Widget.bind('<Enter>', lambda e: window.TKroot.focus_force()) # ウィンドウのテーマ、betterなもののみ記述 sg.theme('LightBrown2'), sg.theme('NeutralBlue'),sg.theme('Kayak'), # データファイルのパス data_file = os.path.join("text_holder", "100_poems.txt") ---> text_holder/100_poems.txt # 最新バージョンにアップグレードする pip install --upgrade PySimpleGUI # from PIL import Image, ImageTkの場合は親元のライブラリーをpipでinstallすること  pip install pillow とすること # Pythonのpathを調べる C:\Users\xxxx\AppData\Local\Programs\Python\Python311 # pipでどんなライブラリーがinstallされているか調べる  C:\Users\xxxx> pip list # pipでどんなライブラリーがinstallされているか調べる  C:\Users\xxxx> pip list ★# 二つのプログラムの違いを調べる https://difff.jp/ # listの[[]]を外す方法(辞書の要素のみ取り出す方法) ・text_list = [['DEYUW AHDJI']]  text = text_list[0][0].strip() #[0][0]のこと print(text)=DEYUW AHDJI # 辞書[]から要素を取り出す ・if event == '-file-': sg.popup(f"選んだfileは、{values['-file-'][0]} ですね。") selected_file = values['-file-'][0] print(selected_file) # 文字列の分割 s_blank = 'one two three\nfour\tfive' #\nは段落、\tはtabで分割 print(s_blank) # one two three # four five print(s_blank.split()) # ['one', 'two', 'three', 'four', 'five'] print(type(s_blank.split())) # 英文文字列をすべて大文字、小文字にする string.ascii_uppercase ---> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' string.ascii_lowercase ---> 'abcdefghijklmnopqrstuvwxyz' # 日本語文字列をすべて子文字にする import jaconv text = "アイウエオ12345ABC" converted_text = jaconv.z2h(text, kana=True, digit=True, ascii=True) print(converted_text) --->出力: アイウエオ12345ABC # ひらがなをカタカナにする import jaconv text = "こんにちは" converted_text = jaconv.hira2kata(text) print(converted_text) ---># 出力: コンニチハ # 文字のサイズ、色を決める layout = [[sg.Text('test', text_color='Blue', background_color='White', font=('Arial',20))]] # 文字設定 layout = [ [ sg.Text('ここに表示させたい文字を入力', font=('Times New Roman',12,"bold"), text_color=("#ffffff"))]] # string.capitalize(文字列) # 各単語の先頭を大文字にする # string.lower(文字列) # すべて小文字にする # string.upper(文字列) # すべて大文字にする # string.join(リスト, セパレータ) # リストを join する #string.strip(文字列) # 先頭と末尾の空白を削除する # string.replace(文字列, 変更したい文字, 変更後の文字) # 置換する # 文章の文字をアプリ上で追加する formatter = string.Formatter() f.format('{0}は口に{1}', '良薬', '苦し') ---> '良薬は口に苦し' # ボタン位置・色を決める  * 位置 left=100、right=10、top=50、bottom=50  [sg.Button('Button', pad=((left,right),(top,bottom)) )] [sg.Button('Button', pad=(left,right))]<--windowの横が広がる。 not so good. [sg.Button('End', pad=((150, 0),(50,0)))] # pad:Endボタンの配置設定 OK [sg.Button('Button', button_color=('blue','red'))] # 複数ボタンを動的配置する button_texts = ["ボタン1", "ボタン2", "ボタン3"] layout = [ [sg.Button(button_texts[0]), sg.Button(button_texts[1]), sg.Button(button_texts[2])]] [sg.Button(button_texts[0]), sg.Button(button_texts[1]), sg.Button(button_texts[2])] # popupを数秒後に消す ・sg.popup_auto_close("5秒後に自動的に閉じるポップアップです", title="ポップアップ", auto_close_duration=5 # popup位置を動かせるようにする if popup_window: popup_event, popup_values = popup_window.read(timeout=100) # ポップアップウィンドウが閉じられた場合 if popup_event == sg.WINDOW_CLOSED or popup_event == 'Close': popup_window.close() popup_window = None # windowに縦にセパレーターを入れる layout = [ [sg.Text('Top')], #セパレーターは他の部品の高さ分と同じなので、縦の点々となる [sg.VerticalSeparator()], [sg.VerticalSeparator()], [sg.VerticalSeparator()], [sg.Text('Middle')], [sg.VerticalSeparator()], [sg.Text('Bottom')]] # EXEファイルを作る, 写真などは別holderにして、exeに添付のこと pyinstaller PySimpleGUI(ストップウオッチ).py --onefile –noconsole # mp3録音bitを変更する変更(128kbit-->64kbit)  https://www.mp3smaller.com/jp/ # with open()でfileを読み込む ①with open("All_208.txt", "r") as f: #,encoding="utf-8") as f: list = f.readlines() word_list = [] for i in list: words = i.split('\t') #tab区分file、文字列中の空白、カンマ、ピリオドなどは混入OK word_list.append(words) #print("27 :", word_list) OK ②with open("All_208.txt", "r") as f: word_list = [line.split('\t') for line in f] # line(txtファイルの)分割(sep)方法 text_file = line.rstrip("\n").rsplit("\t") #rstrip("\n")は段落を取り除く, rsplit("\t")はtabで分割する。 tabの代わりにspaceでも句読点でもOK # MenuBarの作り方 layout=[ [sg.MenuBar([['ファイル',['新規ファイル','ファイルを開く','ユーザー設定', ['設定','拡張機能'],'閉じる']]])] ] layout= [ [sg.MenuBar([['使い方', ['「開始/次へ」で上の句に対応する下の句が下に四個表示されます。', '正しいと思ったボタンをクリックすると回答が表示されます。',' ','戻る']]] # パーツを左・中・右に寄せで配置する layout = [ [frame_left, frame_right], [frame_bottom], [sg.Push(), sg.Text('Tak ver x', text_color='LightBlue')], # 右寄せ [sg.Push(), sg.Text('Right-aligned')], # 右寄せ, 背景色なし [sg.Push(), sg.Button('Center-aligned'), sg.Push()], # 中央寄せ, 背景色あり [sg.Text('Left-aligned'), sg.Push()]] # 左寄せ * installされているライブラリー 10/17/2024 C:\Users\n1tk>pip list Package Version ------------------------- -------------- altgraph 0.17.4 annotated-types 0.7.0 anyio 4.6.0 arrow 1.3.0 binaryornot 0.4.4 certifi 2024.8.30 chardet 5.2.0 charset-normalizer 3.3.2 click 8.1.7 colorama 0.4.6 comtypes 1.4.7 contourpy 1.3.0 cookiecutter 2.6.0 cycler 0.12.1 fastapi 0.115.0 flet 0.24.1 flet-core 0.24.1 flet-runtime 0.24.1 fonttools 4.54.0 h11 0.14.0 httpcore 1.0.5 httptools 0.6.1 httpx 0.27.2 idna 3.10 jaconv 0.4.0 Jinja2 3.1.4 kiwisolver 1.4.7 markdown-it-py 3.0.0 MarkupSafe 2.1.5 matplotlib 3.9.2 mdurl 0.1.2 numpy 2.1.1 oauthlib 3.2.2 otsuvalidator 2.0.1 packaging 23.2 pefile 2024.8.26 pillow 10.4.0 pip 24.2 plum-dispatch 1.7.4 pyasn1 0.6.0 PyAudio 0.2.14 pydantic 2.9.2 pydantic_core 2.23.4 pygame 2.6.0 Pygments 2.18.0 pyinstaller 6.10.0 pyinstaller-hooks-contrib 2024.8 pyparsing 3.1.4 pypiwin32 223 pypng 0.20220715.0 PySimpleGUI 4.70.1 python-dateutil 2.9.0.post0 python-dotenv 1.0.1 python-slugify 8.0.4 pyttsx3 2.97 pywin32 306 pywin32-ctypes 0.2.3 PyYAML 6.0.2 qrcode 7.4.2 repath 0.9.0 requests 2.32.3 rich 13.8.1 rsa 4.9 setuptools 75.1.0 six 1.16.0 sniffio 1.3.1 Spire.Doc 12.7.1 starlette 0.38.6 text-unidecode 1.3 types-python-dateutil 2.9.0.20240906 typing_extensions 4.12.2 urllib3 2.2.3 uvicorn 0.30.6 watchdog 4.0.2 watchfiles 0.24.0 websockets 13.1 ---------------- 10/3/2024 PysimpleGUIのウィジェット(エレメント) PySimpleGUIには様々なウィジェットが用意されています。 一般的なGUIに必要なほぼ全てのウィジェットが揃えられています。 以下に、その一例を示します。詳しくは、公式ページを参照ください。 Text Element(テキスト) InputText Element(インプットテキスト) Button Element(ボタン) ComboBox Element(コンボボックス) Listbox Element(リストボックス) Checkbox Element(チェックボックス) Output Element(アウトプット) Radio Element(ラジオボタン) Spin Element(スピン) Image Element(イメージ領域(GITもしくはPNGのみ) Slider Element(スライダー) Table Element(テーブル) Tab Element(タブ) -------------------------- #部品の基本動作の詳細解説 wedgetと言う https://qiita.com/sunameri22/items/da002d628d7a28cd6e97 https://one-iv.com/programming/python/pythonspysimplegui # GUIレイアウト layout = [ [sg.Radio('Auto', key='AUTO', group_id='0'), sg.Radio('KB', key='KB', group_id='0')], [sg.Text('英単語:'),], [sg.Multiline(size=(40, 10), text_color='Blue', font=('Arial',14, 'bold'), key='INPUT')], ~~~~~ [sg.Push(),sg.Text('JA1FML ver 3.0', text_color='LightBlue') ] ] -------------------------- # 主なライブラリーの説明 import numpy import pyaudio import time import threading import random import pygame import sys Copilot: numpy: 数値計算やデータ処理に特化したライブラリです。 多次元配列や行列演算、乱数生成などの機能を提供しています。 pyaudio: 音声処理に関連するライブラリです。 録音や再生、音声のストリーミングなどを行う際に使用されます。 time: Pythonの標準ライブラリで、時間に関連する機能を提供します。 スリープやタイムスタンプの取得などに利用されます。 threading: スレッドを扱うためのライブラリです。 並行処理を実現するために使用されます。 random: 乱数生成に関する機能を提供します。 ランダムな値を必要とする場合に活用されます。 pygame: ゲーム開発やマルチメディアアプリケーションの作成に適したライブラリです。 グラフィックス、音声、入力処理などをサポートします。 sys: Pythonのシステム関連の機能を提供するライブラリです。 コマンドライン引数の取得やプログラムの終了などに使用されます。 ----------------------------- # 現在のwindowの位置情報を取得する x, y = window.current_location() print(x, y) while True: 上記をここの前に書く ----------------------------- # 縦の分離線を作る 10/9/2024 left_col = [ [sg.Text('左側のコンテナ')], [sg.Multiline('', key='-l_container-', size=(35, 10), enable_events=True)], # イベントを有効にする ] center_col = [ [sg.Text('中央のコンテナ')], [sg.Multiline('', key='-c_container-', size=(25, 5), enable_events=True)], ] right_col = [ [sg.Text('右側のコンテナ')], [sg.Multiline('', key='-r_container-', size=(35, 10), enable_events=True)], ] layout = [ [sg.Column(left_col, element_justification='c'), sg.VSeperator(), sg.Column(center_col, element_justification='c'), sg.VSeperator(), sg.Column(right_col, element_justification='c'),] ] #Endなどで終了するとき: if event == sg.WIN_CLOSED or event == 'End': break ------------------------------- # 部品の状態を見るには、layoutだけ書けばwindowで見ることができる import PySimpleGUI as sg # sliderの状態を見る layout = [ [sg.Slider(range=(0, 100), default_value=50, orientation='h', size=(20, 20), key='slider')] ] window = sg.Window('Colorful Slider', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break window.close() ------------------------------- # ウインドウ位置 win_location = (1000, 300) window = sg.Window('サンプル', layout=layout, location=win_location) *windowのタイトルバーを表示しないが、windowを動かせるにする  windowのlayoutで次を設定 --> no_titlebar=True, grab_anywhere=True, finalize=True

 

PAGE TOP