我有一些代码,它经过一个for循环,应该在tkinter窗口中为我提供9行9列按钮的输出。这些按钮应具有1到9之间的随机数。但是我不希望在同一列和同一行中使用相同的数字。
要完成此操作,我尝试了.pop []和.remove()和del,但没有一个能正常工作。我收到错误row1.remove(“ 4”) ValueError:list.remove(x):x不在列表中。当我尝试删除该数字时,同一行中有2个相同数字。有人可以帮忙吗?
import tkinter as tk
import random
row1 = ["1","2","3","4","5","6","7","8","9"]
col1 = ["1","2","3","4","5","6","7","8","9"]
button = ["1","2","3","4","5","6","7","8","9"]
random.shuffle(button)
root = tk.Tk()
i = 0
for x in range(9):
for y in range(9):
number = random.choice(button)
btn = tk.Button(text=number, bg="white", activebackground="black",
width=2)
btn.grid(row=y, column=x)
i += 1
print(number)
if number == "1":
row1.remove("1")
col1.remove("1")
elif number == "2":
row1.remove("2")
col1.remove("2")
小精灵一路下降到数字9。我只是不想在这里放所有东西。
我希望输出为9 x 9的网格,所有网格都包含1到9的随机数,并且行和列中的数字都不相同。
答案 0 :(得分:1)
Below script with inline code explains a lot. As your matrix is 9x9 I used rows*columns = 81 because you can then ID them all. If only 9 values you get still some doubles. Easily to adjust with adjusting unique_value
. Enjoy simplicity ;P
import tkinter as tk
import random
rows = 9
columns = 9
unique_IDs = 9 # unique IDs per row. If value below e.g. rows
# then backup button list is created to prevent
# an empty list below. Value larger than zero.
root = tk.Tk()
i = 0
# if matrix == unique IDs the amount (rows * columns)IDs is created.
if rows * columns == unique_IDs:
# if unique IDs are smaller than row values below code
# compensates for it by taking total positions in rows as base.
if unique_IDs < rows:
button = [*range(1, ((rows) + 1))]
else:
button = [*range(1, ((unique_IDs) + 1))]
random.shuffle(button)
print ('random : %s' % button) # checks if list random is truly random.
for x in range(rows):
# if matrix != unique IDs the amount of unique_IDs is created.
if (rows * columns) != unique_IDs:
button = [*range(1, ((unique_IDs) + 1))]
random.shuffle(button)
print ('random : %s' % button) # checks if list random is truly random.
for y in range(columns):
# number = random.choice(button) # twice the shuffle dance? Nah!
number = button.pop(0) # just keep popping the soda at first number
# from the randomized button order list
# while it gets smaller and smaller.
btn = tk.Button(text=number, bg="white", activebackground="black", width=2)
btn.grid(row=y, column=x)
i += 1
print(' x, y, value : (%s,%s), %s' % (x, y, number)) # output check!
# likely obsolete code below this comment line.
if number == "1":
row1.remove("1")
col1.remove("1")
elif number == "2":
row1.remove("2")
col1.remove("2")
... snippet ... tk GUI code here ...