0

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.

0

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

I made it work like this. Thanks :)
0

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()

1 Comment

eval is the last thing to try in this situation and there is no need, using dictionaries (or lists) is way better (for example because they don't clutter the namespace)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.