Heexos
Heexos

Reputation: 1

Tkinter: Problems with tag system - How does it work?

I try to code a Minesweeper with Tkinter in Python 3. Look at the code for now:

# -*- coding: utf-8 -*-
from tkinter import *
from random import *

color = "red"
case=[]
fenetre = Tk()

gamezone_x = 10
gamezone_y = 10
mines = 10

def leftclick(event):
    print("Leftclicked at", event.x, event.y)

def rightclick(event):
    print("Rightclicked at", event.x, event.y)

def mines_gen(mines):
    while(mines>0):
        x=randint(0,9)
        y=randint(0,9)
        print(case[x][y])
        Canvas.config(case[x][y], bg="blue")
        Canvas.addtag(case[x][y], "bomb")
        mines-=1

for x in range(gamezone_x):
    case.append([])
    for y in range(gamezone_y):
        case[x].append(Canvas(fenetre, width=20, heigh=20,bg="red"))
        case[x][y].grid(row=x, column=y)
        case[x][y].bind("<1>", leftclick)
        case[x][y].bind("<3>", rightclick)

mines_gen(mines)

fenetre.mainloop()

I can generate my matrix of red canvas and change random canvas in blue. But when I had my "addtag" (in the mines_gen() definition, the program doesn't work and said:

TclError: wrong # args: should be ".!canvas22 addtag tag searchCommand ?arg ...?"

I'm pretty sure that I didn't find how the tags work and how to create/delete/find them and the docs don't help me!

How can I add the tag "bomb" to my blue canvas?

Upvotes: 0

Views: 144

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

Here is a simple change to your code that will set random mines.

You cannot call Canvas() all the time. All you are doing is creating new canvas each time. Instead you should be calling the canvas object you made in the case list. Try the below and let me know if it is what you were attempting to do.

# -*- coding: utf-8 -*-
import tkinter as tk
from random import randint
color = "red"
case = []
fenetre = tk.Tk()

gamezone_x = 10
gamezone_y = 10
mines = 10

def leftclick(event):
    print("Leftclicked at", event.x, event.y)

def rightclick(event):
    print("Rightclicked at", event.x, event.y)

def mines_gen(mines):
    while(mines > 0):
        x=randint(0, 9)
        y=randint(0, 9)
        print(case[x][y])
        case[x][y].config(bg="blue")
        case[x][y].addtag("bomb", "closest", x, y)
        mines -= 1

for x in range(gamezone_x):
    case.append([])
    for y in range(gamezone_y):
        case[x].append(tk.Canvas(fenetre, width=20, heigh=20, bg="red"))
        case[x][y].grid(row=x, column=y)
        case[x][y].bind("<1>", leftclick)
        case[x][y].bind("<3>", rightclick)

mines_gen(mines)

fenetre.mainloop()

Upvotes: 1

Related Questions