【问题标题】:How could i create a set of buttons with a loop in tkinter?我如何在 tkinter 中创建一组带有循环的按钮?
【发布时间】:2021-07-05 23:59:31
【问题描述】:

我正在尝试创建这个程序,基本上我需要在 tkinter 中制作 8 行按钮 但我不知道我怎么能用循环做到这一点 ,没有循环我这样做了:

def decimal():
app = Toplevel(root)
app.title("Traducteur décimal")
app.geometry("400x200")
r1 = Button(app, text="LED 1 ON")
r2 = Button(app, text="LED 1 OFF")
r1.place(x=125,y=0)
r2.place(x=225,y=0)
r3 = Button(app, text="LED 2 ON")
r4 = Button(app, text="LED 2 OFF")
r3.place(x=125, y=40)
r4.place(x=225, y=40)
r5 = Button(app, text="LED 3 ON")
r6 = Button(app, text="LED 3 OFF")
r5.place(x=125, y=80)
r6.place(x=225, y=80)

顺便说一句,我很抱歉英语不好。 谢谢

【问题讨论】:

  • 顺便说一句,我知道这可以通过面向对象编程实现,但我对它的经验很少
  • 使用grid(),你会更快得到更好的答案。

标签: python tkinter button


【解决方案1】:

一种方法是将它们全部放在2-tupleslist 中,并带有for 循环。作为一个列表,你可以通过索引访问它的元素:

buttons = []

x_loc_on, x_loc_off = (125, 225)

y_start = 0
y_offset = 40

commands = [<16 functions here>]

for row in range(8):
    # calculate the pair's y-position based on row
    y_pos_of_row = y_start + row * y_offset

    # get the row number (starts from 1 unlike the variable `row`; so adding 1)
    row_number = row + 1

    # generate the ON button
    button_1 = Button(app, text=f"LED {row_number} ON", command=commands[row])
    button_1.place(x=x_loc_on, y=y_pos_of_row)

    # generate the OFF button
    button_2 = Button(app, text=f"LED {row_number} OFF", command=commands[row+1])
    button_2.place(x=x_loc_off, y=y_pos_of_row)

    # put this row's ON-OFF button pair as a 2-tuple into a list
    buttons.append((button_1, button_2))

然后您可以通过buttons[i][0] 访问ith 行和ON 按钮,并通过buttons[i][1] 访问同一行OFF 按钮。

【讨论】:

  • 谢谢,这确实有效,但我怎样才能将文本修改成它?按钮仅显示 LED 1 ON 和 LED 1 OFF
  • @Tahet 是的,对此感到抱歉.. 现在用f-string 修复。
  • 对不起,这听起来很愚蠢,但我如何与这些新按钮进行交互?我需要将命令参数放入其中
  • @Tahet 不,一点也不愚蠢,但你能更具体一点吗?您是要对所有这些命令一个命令,还是每行一个命令,或者每个按钮一个命令,或者一个命令用于 ON 按钮,一个命令用于 OFF 按钮等。
  • @Tahet 我明白了;然后您可以为所有按钮形成一个包含 16 个命令的列表。然后由于row0变为7,我们可以在for循环的每一轮中用rowrow+1对该列表进行索引,以获得每个按钮的相应命令。编辑了答案。
猜你喜欢
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多