对于一款游戏,我需要用tkinter制作9 x 9的按钮网格。任何想法如何做到这一点? 并且如果按钮可以从1到9中随机选择数字,也将不胜感激。
这与另一个相同,但是我不明白如何使用他们正在使用的东西(例如类)以及如何更改网格以使其为9 x 9。
我试图为此创建一个for循环,但这是行不通的:
import tkinter
row = 1
column = 1
button = ["1","2","3","4","5","6","7","8","9"]
for x in button:
button = tkinter.Button(bg="black", activebackground="white",width=2)
button.grid(row=row, column=column)
column = column + 1
if column == "9":
row = row + 1
column = 1
else:
column = column + 1
谢谢
答案 0 :(得分:0)
我不确定,但我认为您需要3x3的内部9个按钮,所以我为3x3编写了代码。
我使用两个for
循环来做到这一点。而it
可以从清单中获取价值。更容易。
我使用random.shuffle
来获取具有随机顺序的元素的列表。
请勿将Button
关联到您已用于保存列表的变量button
。
import tkinter as tk
import random
button = ["1","2","3","4","5","6","7","8","9"]
random.shuffle(button)
root = tk.Tk()
i = 0
for x in range(3):
for y in range(3):
number = button[i]
btn = tk.Button(text=number, bg="black", activebackground="white", width=2)
btn.grid(row=y, column=x)
i += 1
root.mainloop()
编辑:我也可以使用inter()
和next()
代替i
import tkinter as tk
import random
button = ["1","2","3","4","5","6","7","8","9"]
random.shuffle(button)
root = tk.Tk()
it = iter(button)
for x in range(3):
for y in range(3):
number = next(it)
btn = tk.Button(text=number, bg="black", activebackground="white", width=2)
btn.grid(row=y, column=x)
root.mainloop()