Home > Software design >  Python tkinter: address buttons by using a list
Python tkinter: address buttons by using a list

Time:12-23

I wanted to minimize my code from this:

btn_goto_Sell_A.config(state="normal")
btn_goto_Sell_B.config(state="normal")
btn_goto_Sell_C.config(state="normal")
btn_goto_Buy_A.config(state="normal")
btn_goto_Buy_B.config(state="normal")
btn_goto_Buy_C.config(state="normal")

To this:

def Enable_Button():
    List = [
    "A",
    "B",
    "C"
    ]
    for Letter in List:
        btn_goto_Sell_Letter.config(state="normal")
        btn_goto_Buy_Letter.config(state="normal")

How can i properly talk to my button by building it via my list at the same time? The idea is, instead of writing the same button config, that its just my list and my for-loop.

CodePudding user response:

This can be done with a the eval() function in python:

The following is an example that packs 4 buttons onto the screen in a similar scenario to the one described. the .pack() can easily be substituted with the .config()

from tkinter import *

root = Tk()

buy_A = Button(root, text = "Buy A")
buy_B = Button(root, text = "Buy B")
sell_A = Button(root, text = "Sell A")
sell_B = Button(root, text = "Sell B")

buttons = ["A","B"]
for letter in buttons:
    eval(f"buy_{letter}.pack()")
    eval(f"sell_{letter}.pack()")

root.mainloop()

Another method would be putting all the button objects in a list, and interacting with them directly via the for loop:

from tkinter import *

root = Tk()

buy_A = Button(root, text = "Buy A")
buy_B = Button(root, text = "Buy B")
sell_A = Button(root, text = "Sell A")
sell_B = Button(root, text = "Sell B")

buttons = [buy_A, buy_B, sell_A, sell_B]
for button in buttons:
    button.pack()

root.mainloop()

CodePudding user response:

The smart thing to do is replace your individual variables with a dictionary:

btn_sell = {
    "A": Button(...),
    "B": Button(...),
    "C": Button(...),
}
btn_buy = {
    "A": Button(...),
    "B": Button(...),
    "C": Button(...),
}

Then it becomes trivial to loop over the buttons:

for label in ("A", "B", "C"):
    btn_sell[label].configure(state="normal")
    btn_buy[label].configure(state="normal")
  • Related