提问人:Pete 提问时间:11/1/2023 更新时间:11/1/2023 访问量:66
如何在 Tkinter 中使用循环
How to use loops with Tkinter
问:
我一直在尝试获得一个循环以在 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
这是我的代码,我希望它能成为这一行,但它什么也没做
答:
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
这是正确的语法(不会引发 ),但拥有 .SyntaxError
range(-25)
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()
创建此应用程序:
评论
range(1-26)
range(-26)