0

im programming a chess game with tkinter in Python. I use a Tk() with 64 Labels for the fields. Also i bind my Tk() to a function which get x and y coordinate by clicking on the window. The problem is i get the x and y coordinate of the labels back. chess game

wn = Tk()
wn.geometry('600x600')
# bind action event
x_click = ''
frame = Frame(master=wn, width=600, height=600)
frame.pack()
def clicked(event):
    global x_click
    x_click= event.x
    print(x_click)
frame.bind("<Button-1>", clicked)

...

class GUI:
     def setSpielfeld(self):

        # start with index 1, init gamefield with dark and bright fields, x_start and y_start moves the complete gamefield
        self.label_gamefields.append('')
        for i in range (1,65):
            self.label_gamefields.append('')
            if self.dasSpielfeld.gamecolor[i] == 'dark':
                self.label_gamefields[i] = Label(master=wn, image=self.image_dark)
                self.label_gamefields[i].place(x=self.dasSpielfeld.position_x[i] + x_start, y=self.dasSpielfeld.position_y[i] + y_start, width=39, height=39)

            else:
                self.label_gamefields[i] = Label(master=wn, image=self.image_bright)
                self.label_gamefields[i].place(x=self.dasSpielfeld.position_x[i] + x_start, y=self.dasSpielfeld.position_y[i] + y_start, width=39,
                                          height=39)

Anybody knowes what to do?

Thank you very much

Flo
  • 1
  • ***"i get the x and y coordinate of the labels back"***: Couldn't imagin that, if you do `frame.bind(...`. But you can compute from `event.x` and `event.y` to find the relevant `Label`. Consider to use [`Canvas`](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.find_closest-method), there are all relevant `.find_...` methods implemented. – stovfl Nov 15 '19 at 22:04
  • Hey, thank you very much for your response. I tried it, but i had a problem with the index of my Labels. I didnt chose them exactly like the index of my gamefield list. Anyway, i found a other solution. I use Buttons instead of Labels. The buttons call the command function which has the parameter position. The parameter positions is the index of the gamefield. command =lambda:clicked(position=i) – Flo Nov 16 '19 at 11:00
  • ***`command =lambda:clicked(position=i)`***: This looks erroneous, read [Python and Tkinter lambda function](https://stackoverflow.com/a/11005426/7414759) – stovfl Nov 16 '19 at 12:33

0 Answers0