我如何在 tkinter 中创建一组带有循环的按钮?

编程入门 行业动态 更新时间:2024-10-22 23:42:43
本文介绍了我如何在 tkinter 中创建一组带有循环的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

I have this program i'm trying to create, and basically i need to make 8 rows of buttons in tkinter but i can't figure out how i could do this with a loop , without a loop i did this :

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)

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

By the way i'm sorry for the bad English. Thanks

推荐答案

一种方法是将它们全部放入带有 2-tupleslistfor 循环.作为一个列表,您可以通过索引访问其元素:

A way is to put them all in a list of 2-tuples with a for loop. Being a list, you can access its elments after via indexing:

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]和同一行OFF<来访问ith row和ON按钮/code> 按钮通过 buttons[i][1].

Then you can access ith row and ON button via buttons[i][0] and same row OFF button via buttons[i][1].

这篇关于我如何在 tkinter 中创建一组带有循环的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 06:41:52,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   如何在   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!