multiple buttons in one line of code in tkinter

给你一囗甜甜゛ 提交于 2020-02-04 05:35:14

问题


I need to create 200 check buttons in Tkinter, as I'm creating a seat selection screen. Is there a way of creating all of these buttons without having to type them out line by line, like you can in pygame? so far I've tried this but it doesn't seem to work. (I am not a super smart coder so it may be a silly mistake).


root = tk.Tk()

frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)
button = list()
for i in range(4):
button.append(tk.Button(frame1, image=karirano, command=partial(klik, i)))
    button[-1].grid(row=0,column=i)
root.mainloop()```

回答1:


Yes, you can create buttons in a loop. If I were doing a seating chart, I would start by defining what it looks like with a simple data structure that lets you easily visualize the layout.

For example:

rows = {
    "a": "  xxxx xxxxxxxx xxxx",
    "b": "xxxxxx xxxxxxxx xxxxxx",
    "c": "xxxxxx xxxxxxxx xxxxxx",
}

You can then iterate over this data, placing a seat everywhere there is an "x".

For example:

for row_number, row_letter in enumerate(rows.keys()):
    for seat_number, c in enumerate(rows[row_letter]):
        if c == "x":
            seat = tk.Button(frame1, ...)
            seat.grid(row=row_number, column=seat_number)



回答2:


it appears it was just a syntax error, the code works how I wanted it to now.



来源:https://stackoverflow.com/questions/59901272/multiple-buttons-in-one-line-of-code-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!