SolvedPySimpleGUI Simple button state On/Off - tkinter way shown but same result in PySimpleGUI possible ?

Loving the simplicity of PySimpleGUI, however........

Here is my version of a simple Tkinter button state code

when a button is pressed, it changes state & colour. It outputs a variable state.

Is this possible in PySimpleGUI ?

Have not been able to do this as of yet. Any ideas how to replicate this simple task

in PySimpleGUI ?

TKinter Code shown below .

import PySimpleGUI as sg
try:
import tkinter as tk
from tkinter import ttk
except ImportError:
import Tkinter as tk
import ttk

def toggle1():
if button1.config('text')[-1] =='ON':
button1.config(text='OFF', bg="red",activebackground="red",textvariable=0)
print(button1.config('textvariable')[-1])
else:
button1.config(text='ON', bg="green",activebackground="green",textvariable=1)
print(button1.config('textvariable')[-1])

root = tk.Tk()
button1 = tk.Button(
text="OFF",
width=12,
height=1,
borderwidth=0,
command=toggle1 ,
relief="raised",
state="normal",
bg="red",
activebackground="red",
repeatdelay=1
)
button1.pack(pady=5)
root.mainloop()

32 Answers

✔️Accepted Answer

Here's some code that does a simple toggle button. It does it without the relief settings, using only colors.

You can run it on repl.it by going here:
https://repl.it/@PySimpleGUI/Toggle-Button

And you can run the Web version (with only 1 line of code changed) here:
https://repl.it/@PySimpleGUI/Toggle-Button-Web

Also, the code will run, as is, on the web by changing the import statement ONLY. 👍 It looks pretty good on the web too.

import PySimpleGUI as sg

layout = [[sg.Text('A toggle button example')],
          [sg.Button('On', size=(3,1), button_color=('white', 'green'), key='_B_'), sg.Button('Exit')]]

window = sg.Window('Window Title', layout)

down = True

while True:             # Event Loop
    event, values = window.Read()
    if event in (None, 'Exit'):
        break
    if event == '_B_':
        down = not down
        window.Element('_B_').Update(('Off','On')[down], button_color=(('white', ('red', 'green')[down])))

window.Close()

Related Issues:

4
PySimpleGUI Updating form layouts
OK it's DONE! Please get a new PySimpleGUI.py file the Dev-active branch Is it possible for the form...
3
PySimpleGUI Simple button state On/Off - tkinter way shown but same result in PySimpleGUI possible ?
Here's some code that does a simple toggle button It does it without the relief settings using only ...
3
PySimpleGUI [Request] Play gifs in PySimpleGUI
This one took a while to get around to doing but it's COMPLETE released to PyPI and ready to use ...
94
react chartjs 2 Mix chart, labels.slice is not a function error
After fiddling with this for a little while I found a way to fix the example It is very easy and I d...
77
react chartjs 2 Defaults creating error
got the same issue solve it by change the chart.js: ^2.9.4 in your package.json then delete node mod...
11
react chartjs 2 Testing with jest / enzyme / jsdom - Failed to create chart: can't acquire context from the given item
Workaround is to mock out the chart for enzyme mounting (or just use a shallow wrapper) ...
11
WidescreenFixesPack [NFSUC] HUD Aspect Ratio and FoV Issues on Ultrawide (and Possibly Other Crop Aspect Ratio) Screens
@ThirteenAG Let's hit the reset button and try this again I've tested the following information with...
9
open_spiel OpenSpiel 1.0: Call for Beta Testers of Binary Pip Wheel
Alright the binary distribution wheel is now live so you should not need the ==1.0.0rc1 anymore ...
4
WidescreenFixesPack [SH2] Options/Inventory Font Resolution
Hi guys The next update release for Silent Hill 2: Enhanced Edition will feature all-new title and s...
264
tqdm Jupyterlab and tqdm_notebook
I confirm this problem on my environment but it is upstream so IMHO nothing can be done on tqdm Plea...
158
dbeaver "invalid privatekey" connecting through SSH tunnel
Run this on your key to convert it to RSA private key Helped me ssh-keygen -p -m PEM -f ~/.ssh/id_rs...
78
dbeaver Postgres connection error
@lcustodio on the SSL page set SSL mode: require and either leave the SSL Factory blank or use the o...
60
dbeaver Create a PPA for updating dbeaver under ubuntu
First DBeaver CE PPA is here: https://launchpad.net/~serge-rider/+archive/ubuntu/dbeaver-ce Usage: I...
50
Open3D ImportError: /lib64/libm.so.6: version 'GLIBC_2.27' not found
I met the same question after pip install and I solved it by specifying a version python -m pip inst...
47
tqdm How to update single progress bar in multiprocessing map()
from https://stackoverflow.com/questions/41920124/multiprocessing-use-tqdm-to-display-a-progress-bar...
46
flameshot FlameShot doesn't start, no errors
Having the same issues But calling flameshot gui shows something. Hi I've installed flameshot on gen...
36
dbeaver dbeaver 6.3.4 on macOS 10.15.3 Catalina fails to open with message "Failed to create the Java Virtual Machine."
@jesimone57 As you mentioned there is a problem when DBeaver runs on adoptopjtjdk 11.0.6 In my case ...
33
dbeaver Failed to create java virtual machine .
Was able to get Dbeaver to start with an installation of Oracle JDK 8 update 202 on my Mac in /Libra...
21
dbeaver mac os bigsur can not run dbeaver
Try out linking the below - this works irrespective of version of DBeaver (I have tested with 7.2.4 ...
21
oni Oni does not launch Neovim.
Fixed by creating ~/.config/oni/config.js with following content: Oni Version: 0.3.6 Neovim Version ...
20
dbeaver app can not run by 'openjdk 14' on Mac
For those like me who installed these two apps through Homebrew cask: Dbeaver 7.0.1 (brew cask insta...
18
imgui rs Discussion: maintainer change
And it's done! I hope everybody is happy with the direction I take imgui-rs! I've decided to stop ma...
16
Open3D JVisualizer python27 AttributeError: 'module' object has no attribute 'PointCloud'
pip install open3d-python fixes the no attribute 'PointCloud' problem for me I'm using Ubuntu 16.04 ...
16
imgui New Tables API (alpha available for testing)
Basic Usage (Edited Jan 8 2021) There's a large amount of demo contents in Demo > Tables & Columns p...
15
dbeaver TLS 1.0 and TLS 1.1 support
Hi @ShadelessFox Thank you It worked now As you have mentioned TLS 1.0/1.1 are disabled by default i...
14
tqdm tqdm.pandas() ImportError: cannot import 'PanelGroupBy'
should be fixed in tqdm>=4.23.4 When using tqdm v4.23.3 and pandas v0.23.0 I get this error: It look...
12
Cura Unable to open any STL in 4.7
It is not very easily hackable but it is possible The following instructions come with no warranty p...
10
dbeaver "Utility mysqldump not found" on Fedora with Flatpak
As noted in this flathub issue there are extensions available for the dbeaver package on flathub tha...
10
tqdm Wrong output in Windows console
That's partial unicode support You can probably fix it with tqdm(... ascii=True) ...
8
lvgl [v7.0] General discussion
I've added lv_canvas_blur_hor/ver. Schedule Release candidate: 1 May Release: 18 May Docs The docs f...
6
imgui Another Plotting Widget
Thanks! I hope it works well for you I've add two functions IsPlotHovered and GetPlotMousePos ...
5
flameshot Flameshot not launching when using Wayland
For @AkechiShiro Flameshot version 0.6.0-9(Debian) Describe the bug The commands flameshot gui or fl...
5
Open3D Open 3D package for Apple silicon M1
Hi @DikZoo you may try this experimental build let me know if it works for you ...
4
Cura Z-axis not moving up as it should in new Cura 3.6.0
Great that confirms the bug and it has to be one of the oddest bugs I've seen in a long time ...
4
dbeaver Dbeaver issue with Official Java SE 9 release
Eidt /Applications/DBeaver.app/Contents/Info.plist Add somethins like this : then you don't need to ...
4
gui.cs I want to draw horizontal line (HLine)
Here is a HorizontalLineView class I just created now for you :) this should be much more elegant an...
3
Cura 2.6 Filament Diameter and Nozzle Temp Ignored
Thanks for reporting I'm using Cura 2.6 on Windows this is a clean install with no previous profiles...
3
Cura [3.5] Temperature is not correct in the GCode
Does M104 S{material_print_temperature 0} work for you? I Have the following entry in the Start GCod...
3
dbeaver private key conversion doesn't seem to work without password
Hey @ShadelessFox First I tried with 7.2.4 and I had the same issue but in 7.2.5 everything is fine ...
3
dbeaver unable to locate its companion shared library
I have investigated the issue DEB file is missing all *.so files (maybe more but they are most impor...
3
Open3D Convert Realsense poincloud in Open3D pointcloud
To test te most efficient way to show in realtime the pointcloud from Realsense ...
3
go app Example crashing right away after go build or go run
@dmonay @mcastilho @euforic Hey guys I got some problems with the last Xcode and go updates Crash wh...
3
x11docker orchestrating x11docker docker-compose?
you must get tired of people calling you a genius...! here is the d-c file that worked: I just lifte...
3
x11docker Support for webcam sharing
Good news! cheese now runs without a privileged setup I found in #86 that cheese and gnome-ring need...
22
react native web The future of React Native for Web
Closing as 0.13 is released Over the next few months I'll be working through some significant change...
20
react native web 0.14 canary
🥳 The PR for Modal is now merged into @next - so the canary should have that good to go! Seems to b...
15
react native web Touchable issues
@RichardLindhout I use custom touchables right now and it works by using something like this: Edit: ...
15
react native web Exporting types
Some good news: @types/react-native seems to have implemented the fix suggested here ...
13
react native web Support for Electron as a target
I like the idea Is your feature request related to a problem? Please describe ...
12
react native web FlatList performance: Scrolling is buggy and not smooth when virtualization is enabled
PureComponent keyExtractor Thanks but I use that already getItemLayout Just tried unfortunately didn...