这可以通过
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()