Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python tkinter button dynamic button command

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 :: chi square test contingency table python 
Python :: soustraire deux listes python 
Python :: python string interpolation 
Python :: separate words in a text to make a list python 
Python :: leetcode matrix diagonal sum in python 
Python :: # enumerate 
Python :: how to make a window python 
Python :: how to merge two column pandas 
Python :: flask on gevent over https 
Python :: how to declare private attribute in python 
Python :: identity matrix python 
Python :: django login url 
Python :: file storage django 
Python :: Math Module pow() Function in python 
Python :: replace pandas column values based on condition 
Python :: ImportError: cannot import name include 
Python :: keyboard write python 
Python :: python library for downsampling a photo 
Python :: python compare each item of one list 
Python :: isupper() in python 
Python :: qt set focus 
Python :: get first element of array python 
Python :: docstrings in python 
Python :: Remove whitespace from str 
Python :: datetime print the current time 
Python :: compare lists element wise python 
Python :: is python a scripting language 
Python :: python internship 
Python :: beautifulsoup remove empty tags 
Python :: how to use ternary operater in python 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =