是否有办法使对象与循环或其他东西?



我正在尝试可视化二进制搜索算法,我需要创建10个"支柱";与tkinter。我是这样做的(下面的代码),但我有一种感觉,有一个更好的方法来做同样的事情。我已经尝试过用for循环和exec命令制作柱子,但我似乎没有让它工作。

import tkinter as tk

class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("1000x600")
self.resizable(False, False)
self.title("Binary Search Algorithm")
self.p0 = tk.Label(self, text=f"I am pillar 0", bg="grey")
self.p1 = tk.Label(self, text=f"I am pillar 1", bg="grey")
self.p2 = tk.Label(self, text=f"I am pillar 2", bg="grey")
self.p3 = tk.Label(self, text=f"I am pillar 3", bg="grey")
self.p4 = tk.Label(self, text=f"I am pillar 4", bg="grey")
self.p5 = tk.Label(self, text=f"I am pillar 5", bg="grey")
self.p6 = tk.Label(self, text=f"I am pillar 6", bg="grey")
self.p7 = tk.Label(self, text=f"I am pillar 7", bg="grey")
self.p8 = tk.Label(self, text=f"I am pillar 8", bg="grey")
self.p9 = tk.Label(self, text=f"I am pillar 9", bg="grey")
self.p0.place(x=0, y=500)
self.p1.place(x=100, y=500)
self.p2.place(x=200, y=500)
self.p3.place(x=300, y=500)
self.p4.place(x=400, y=500)
self.p5.place(x=500, y=500)
self.p6.place(x=600, y=500)
self.p7.place(x=700, y=500)
self.p8.place(x=800, y=500)
self.p9.place(x=900, y=500)
if __name__ == "__main__":
Display = MainWindow()
Display.mainloop()

是的,保持一个标签列表或字典,而不是许多单独的属性。

def __init__(self):
super().__init__()
self.geometry("1000x600")
self.resizable(False, False)
self.title("Binary Search Algorithm")

self.ps = []
for i in range(10):
p = tk.Label(self, text=f"I am pillar {i}", bg="grey")
p.place(x=100*i, y=500)
self.ps.append(p)

在代码的其余部分,您可以将(例如)self.p0替换为self.ps[0],对于其他数字属性也是如此。

是的,你可以做一些类似

for i, x in enumerate(x_values):
setattr(self, f'p{i}', x)

虽然我不知道tkinter需要什么,但是我会重新考虑这个逻辑。

最新更新