python在运行时生成GUI
我想在运行时生成python GUI 假设列表是来自数据库的一些数据,我希望每个db行都有按钮。 我该怎么做python在运行时生成GUI,python,tkinter,runtime,Python,Tkinter,Runtime,我想在运行时生成python GUI 假设列表是来自数据库的一些数据,我希望每个db行都有按钮。 我该怎么做 import tkinter as tk root = tk.Tk() root.geometry("800x480") def cmdLastafel(button): button["text"] = "deze" lst= ["A","B","C"] cnt = 0 for i in lst: cnt +=1 btn = tk.Button(roo
import tkinter as tk
root = tk.Tk()
root.geometry("800x480")
def cmdLastafel(button):
button["text"] = "deze"
lst= ["A","B","C"]
cnt = 0
for i in lst:
cnt +=1
btn = tk.Button(root)
btn["text"] = i
btn.configure(command=lambda: cmdLastafel(btn))
btn.grid(row=cnt,column=0)
root.mainloop()
这给了我3个按钮,但当我按A时,C文本被更改。。
我有一个.net背景,在那里我可以通过在for循环的开头创建一个新按钮,并在循环的末尾将该按钮存储在一个列表中来解决这个问题。
但是我不知道如何在python中强制创建一个新的按钮,或者如何创建一个空的按钮列表。您可以在
列表中创建按钮
下面是一个例子:
import tkinter as tk
root = tk.Tk()
root.geometry("800x480")
def cmdLastafel(button):
button.config(text = "deze")
lst= ["A","B","C"]
buttons = []
for cnt, i in enumerate(lst):
buttons.append(tk.Button(root,
text = i))
# buttons[-1] refers to the last item in the list, so the button we just appended.
# lambda btn=buttons[-1], stores the last button at the time of iteration to btn.
buttons[-1].config(command=lambda btn=buttons[-1]: cmdLastafel(btn))
buttons[-1].grid(row=cnt,column=0)
root.mainloop()
阅读