lundi 8 avril 2019

ValueError: list.remove(x): x not in list error how to fix?

I have some code where it goes through a for loop and should give me and output of 9 rows and 9 columns of buttons in a tkinter window. These buttons should have a random number in them ranging from 1 to 9. But I do not want the same number in the same column and row to be the same.

To acomplish this I have tried .pop[] and .remove() and del but none have properly worked. I get the error row1.remove("4") ValueError: list.remove(x): x not in list. And there is 2 of the same number in the same row when I tried to remove that number. Can somebody please help?

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")

The elif goes all the way down to the number 9 by the way. I just didnt want all of it in here.

I expect the output to be a 9 x 9 grid all containing a random number ranging from 1 to 9 and none of the numbers to be the same in a row and column.




Aucun commentaire:

Enregistrer un commentaire