因此,基本上我被要求创建一个零交叉游戏界面,但是我似乎无法弄清楚如何基于鼠标单击来显示一个点。到目前为止,我可以根据单击鼠标的位置来检索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()
答案 0 :(得分: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坐标的中心点上绘制它即可。