Py学习  »  Python

Python tkinter:使用列表的地址按钮

Rangerocker • 3 年前 • 1265 次点击  

我想从以下方面最小化我的代码:

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

为此:

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

如何通过同时通过列表创建按钮来正确地与按钮对话? 其想法是,与其编写相同的按钮配置,不如只编写我的列表和for循环。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128642
 
1265 次点击  
文章 [ 2 ]  |  最新文章 3 年前
SlavaCat
Reply   •   1 楼
SlavaCat    3 年前

这可以通过 eval() python中的函数:

下面是一个示例,在与上述场景类似的情况下,将4个按钮打包到屏幕上。这个 .pack() 可以很容易地用 .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()

另一种方法是将所有按钮对象放在一个列表中,并通过 for 循环:

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()
Bryan Oakley
Reply   •   2 楼
Bryan Oakley    3 年前

聪明的做法是用字典替换单个变量:

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

然后在按钮上循环就变得很简单了:

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