Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python tkinter dynamic toggle button

import tkinter  as tk

root = tk.Tk()
root.geometry("500x300")

"""
Images:
https://drive.google.com/file/d/1tlLl2hjPq38mc_c_PpMhkKDlP1HqvDY5/view
https://drive.google.com/file/d/1bejSlQtIokdQw7d-5Qbqw1X3Sw5Y2bWO/view
"""
# The following 2 'PhotoImage' reads CANNOT be within bellow 'UpdateValue' method
# ( won't read the image into memory quick enough. )
# Option A) use a global variable  
# Option B) create class object ( self.on, self.off ) 
on = tk.PhotoImage(file =  "button_on.png")
off = tk.PhotoImage(file = "button_off.png")
 
def UpdateValue(ar_wid, ar_var,jj):
    if ar_var[jj].get() == '0':
        img = on  
        ar_var[jj].set('1')
    else:
       img = off
       ar_var[jj].set('0') 
    ar_wid[jj].config(image = img)

arr_widgets = []
arr_vars = []
# create 5 toggle buttons
for i in range(5):
    ThisVar = tk.StringVar(master=root, name= f'button_{i}', value='1')
    on_button = tk.Button(root, image = on, bd = 0, textvariable=ThisVar)
    on_button.config(command=  lambda j=i : UpdateValue(arr_widgets, arr_vars, j) )
    on_button.pack(pady = 10)
    arr_widgets.append(on_button)
    arr_vars.append(ThisVar)

root.mainloop()
Comment

PREVIOUS NEXT
Code Example
Python :: regularization pytorch 
Python :: python panda count excel sheet 
Python :: python sort 
Python :: repr() in python 
Python :: matrix diagonal sum python 
Python :: basic python programs 
Python :: how to move the last column to the first column in pandas 
Python :: Python using webbrowser 
Python :: Use a callable instead, e.g., use `dict` instead of `{}` 
Python :: discord.py get user id 
Python :: python sort by length and alphabetically 
Python :: login url 
Python :: How to filter with Regex in Django ORM 
Python :: django create super user 
Python :: python is instance 
Python :: access to specific column array numpy 
Python :: write python 
Python :: Customize color stacked bar chart matplotlib 
Python :: groupby and list 
Python :: ubuntu python3 as python 
Python :: pyqt setfocus 
Python :: python how to inspect pyd for functions 
Python :: pandas split tuple column 
Python :: calculate the shortest path of a graph in python 
Python :: django background_task 
Python :: elementwise comparison list python 
Python :: how to use sin inverse and cos inverse in python 
Python :: spacy get number of tokens 
Python :: how to print 2 list in python as table 
Python :: dataframe summary | dataframe info 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =