根据鼠标点击发生tkinter的位置显示一个点

问题描述 投票:-1回答:1

所以基本上我被要求创建一个naughts和十字架游戏界面,但我似乎无法弄清楚如何基于鼠标点击显示一个点。到目前为止,我可以根据moused被点击的位置来检索x和y,但是我不能在这个位置显示一个点。我的代码如下,提前感谢:

from tkinter import *

class Window(Tk):
    def __init__(self):
         Tk.__init__(self)

         self.mygui()



def mygui(self):
    self.title('Naughts and Crosses')
    self.geometry('600x400+700+300')

    self.bind('<Button-1>', self.get_location)

    #creating a naughts and crosses board

    canvas = Canvas(self, width=1000, height=1000)

    canvas.create_line(100, 140, 500, 140)
    canvas.create_line(100, 250,500, 250)

    canvas.create_line(220, 50, 220, 350)
    canvas.create_line(370, 50, 370, 350)

    canvas.pack()

def get_location(self, eventorigin):
    x = eventorigin.x
    y = eventorigin.y
    # x and y will return three figure coordinates, this is where i am 
    stuck.

Window().mainloop()
python-3.x tkinter
1个回答
0
投票

所以这实际上是相当直接的。我将布置步骤,让你开始第一个盒子,然后其余部分应该很容易。

我从左上角和中间框开始,使用你用来获得每个框的右上角和左下角的线坐标。然后我检查鼠标点击坐标是否位于这些点之间,因此在给定的框内。

from tkinter import *

class Window(Tk):
    def __init__(self):
         Tk.__init__(self)

         self.mygui()

         # Define the bounds of each box based on the lines drawn in mygui
         self.topleft = [(100,220), (50, 140)]
         self.topmiddle = [(220, 370), (50, 140)]

    def mygui(self):
        self.title('Naughts and Crosses')
        self.geometry('600x400+700+300')

        self.bind('<Button-1>', self.get_location)

        #creating a naughts and crosses board

        canvas = Canvas(self, width=1000, height=1000)

        canvas.create_line(100, 140, 500, 140)
        canvas.create_line(100, 250,500, 250)

        canvas.create_line(220, 50, 220, 350)
        canvas.create_line(370, 50, 370, 350)

        canvas.pack()

    def get_location(self, eventorigin):
        x = eventorigin.x
        y = eventorigin.y
        # x and y will return three figure coordinates, this is where i am stuck.

        print(x, y)
        print(self.topleft)
        print(self.topmiddle)

        # Check if the mouse click is in the top left box
        if(x > self.topleft[0][0] and x < self.topleft[0][1]):
          if(y > self.topleft[1][0] and y < self.topleft[1][1]):
              print("In top left")
        # Check if the mouse click is in the top middle box
        if(x > self.topmiddle[0][0] and x < self.topmiddle[0][1]):
          if(y > self.topmiddle[1][0] and y < self.topmiddle[1][1]):
              print("In top middle")


Window().mainloop()

还有很多其他方法可以做到这一点,但这应该足以让你开始。

正如您在我的示例中所见,每个框都有两个定义点。要在该框中绘制一个x,只需将这些点中的一条线绘制到另一条点,然后绘制另一条垂直于该线的线。这不应该太难。要在中心绘制一个点,只需将其绘制在框的两个定义x坐标的中心点上。

© www.soinside.com 2019 - 2024. All rights reserved.