如何在 Tkinter 中使用循环

How to use loops with Tkinter

提问人:Pete 提问时间:11/1/2023 更新时间:11/1/2023 访问量:66

问:

我一直在尝试获得一个循环以在 Tkinter 窗口上列出按钮,但我不知道这是否可能,或者我的代码是否不正确

count = 1
    height = 300
    width = 600
    while count > 26:
        for i in range(1-26):
            square = Button(win, text='', height=1, width=2)
            square.place(x=width, y=height)
            height = height + 20
            width = width + 30
            count = count + 1

这是我的代码,我希望它能成为这一行,但它什么也没做

python 循环 变量 tkinter

评论

0赞 Andrew Allaire 11/1/2023
按下按钮时,您不需要做任何事情吗?在任何情况下,您的代码片段在其第二行 atm 上都有无效的缩进。还必须假设您已经赢得了一个 Tk() 对象......你有没有记得在之后调用win.mainloop()?
0赞 toyota Supra 11/5/2023
你有错别字错误应该是range(1-26)range(-26)

答:

1赞 zach 11/1/2023 #1

你有两个循环。while 循环中的任何内容都不会运行,因为它仅在 count 大于 26 但 count 为 1 时运行。for 循环对 range 使用了错误的语法。仔细检查范围的语法,以及如何在 tkinter 中创建按钮

https://www.w3schools.com/python/gloss_python_for_range.asp https://www.pythonguis.com/tutorials/create-buttons-in-tkinter/

评论

1赞 TheLizzard 11/1/2023
这是正确的语法(不会引发 ),但拥有 .SyntaxErrorrange(-25)
0赞 Community 11/2/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。
2赞 Andrej Kesely 11/1/2023 #2

下面是一个简单的示例,如何将按钮“排成一列”(您可以根据需要对其进行自定义):

from tkinter import *

win = Tk()
win.title("Simple App with buttons")
win.geometry("800x300")


def place_buttons(win, x, y, how_much=10):
    for _ in range(how_much):
        square = Button(win, text="", height=1, width=2)
        square.place(x=x, y=y)
        x += 80


place_buttons(win, 10, 100)
win.mainloop()

创建此应用程序:

enter image description here