简体   繁体   English

Tkinter 获取坐标的平均值

[英]Tkinter getting the average of coordinates

I have looked up similiar topics but couldn't find an answer to the problem I have been dealing with.我查找了类似的主题,但找不到我一直在处理的问题的答案。 Let me completely explain the situation.让我完整地解释一下情况。

I have made a python GUI with ovals and I want to get the coordinates of these ovals.我用椭圆制作了一个 python GUI,我想获得这些椭圆的坐标。 When they are tagged.当它们被标记时。

I have been successful on getting coordinates, but it seems tkinter gives me 4 values (x1,x2,y1,y2).我已经成功获得坐标,但似乎 tkinter 给了我 4 个值(x1、x2、y1、y2)。 To which I prefer having only x and y coordinates.我更喜欢只有 x 和 y 坐标。

As I have consulted another topic to solve this problem, I have been made clear that I haven't myself clear.由于我已经咨询了另一个主题来解决此问题,因此我已明确表示我自己还不清楚。 And my question was just confusing.我的问题只是令人困惑。

So I have 92 ovals and I want to get only x and ys using coordinate function.所以我有 92 个椭圆,我只想使用坐标函数得到 x 和 ys。

Here is the complete code( I have deleted unnecessary details.这是完整的代码(我删除了不必要的细节。

from tkinter import Tk
import tkinter

top = tkinter.Tk()

canvas = tkinter.Canvas(top, bg="white", height=1000, width=1000)
liste=[]
liste5=[]
liste6=[]
liste7=[]
X=[]
a=0
for i in range(4):
    for ii in range(12):
        y=canvas.create_oval(10 + ii * 50, 10 + i * 100, 40 + ii * 50, 40 + i * 100, fill="blue", activefill="red")
        if ii != 11:
            x=canvas.create_oval(25 + ii * 50, 60 + i * 100, 55 + ii * 50, 90 + i * 100, fill="blue", activefill="red")

def groups(glist, numPerGroup=2):
    result = []

    i = 0
    cur = []
    for item in glist:
        if not i < numPerGroup:
            result.append(cur)
            cur = []
            i = 0

        cur.append(item)
        i += 1

    if cur:
        result.append(cur)

    return result


def average(points):
    aver = [0, 0]

    for point in points:
        aver[0] += point[0]
        aver[1] += point[1]

    return aver[0] / len(points), aver[1] / len(points)

class RectTracker:

    def __init__(self, canvas):
        self.canvas = canvas
        self.item = None

    def draw(self, start, end, **opts): #seçim için oluşan rectanglei oluşuturuyor..
        """Draw the rectangle"""
        return self.canvas.create_rectangle(*(list(start) + list(end)), **opts)#this one makes us draw the rectangle

    def autodraw(self, **opts): #classın içindeki çizim fonksiyonu aşağıda autodraw fonksiyonuyla bunun çağrıyor.
        """Setup automatic drawing; supports command option"""
        self.start = None
        self.canvas.bind("<Button-1>", self.__update, '+')
        self.canvas.bind("<B1-Motion>", self.__update, '+')
        self.canvas.bind("<ButtonRelease-1>", self.__stop, '+')
#        self.canvas.bind("<Button-1>", mm.select)
#        self.canvas.bind("<Button-1>",find_enclosed(x1,y1,x2,y2))
        self._command = opts.pop('command', lambda *args: None)
        self.rectopts = opts

    def __update(self, event):
        if not self.start:
            self.start = [event.x, event.y]
            return

        if self.item is not None:
            self.canvas.delete(self.item)
        self.item = self.draw(self.start, (event.x, event.y), **self.rectopts)
        self._command(self.start, (event.x, event.y))

    def __stop(self, event):
        self.start = None
        self.canvas.delete(self.item)
        self.item = None

    def hit_test(self, start, end, tags=None, ignoretags=None, ignore=[]):
        """
        Check to see if there are items between the start and end
        """
        ignore = set(ignore)
        ignore.update([self.item])

        # first filter all of the items in the canvas
        if isinstance(tags, str):
            tags = [tags]

        if tags:
            tocheck = []
            for tag in tags:
                tocheck.extend(self.canvas.find_withtag(tag))
        else:
            tocheck = self.canvas.find_all()
        tocheck = [x for x in tocheck if x != self.item]
        if ignoretags:
            if not hasattr(ignoretags, '__iter__'):
                ignoretags = [ignoretags]
            tocheck = [x for x in tocheck if x not in self.canvas.find_withtag(it) for it in ignoretags]

        self.items = tocheck

        # then figure out the box
        xlow = min(start[0], end[0])
        xhigh = max(start[0], end[0])

        ylow = min(start[1], end[1])
        yhigh = max(start[1], end[1])

        items = []
        for item in tocheck:
            if item not in ignore:
                x, y = average(groups(self.canvas.coords(item)))
                if (xlow < x < xhigh) and (ylow < y < yhigh):
                    items.append(item)

        return items

def onDrag(start, end):#ondrag fonksiyonuyla kareyi oluşturduğunu görebiliriz.
    canvas.itemconfig('kirmizi',tags=('blue'))
    global x, y
    items = rect.hit_test(start, end) 
    for x in rect.items:
        if x not in items:
            canvas.itemconfig(x, fill='blue')
        else:
            canvas.itemconfig(x, fill='red')
            canvas.itemconfig(x,tags=('kirmizi'))
    liste.append(canvas.find_withtag('kirmizi'))
    liste7.append(canvas.coords(canvas.find_withtag('kirmizi')))

      #  liste.append(canv.find_withtag('kirmizi'))
    #soneleman=liste[-1]
rect=RectTracker(canvas)
rect.autodraw(fill="", width=2, command=onDrag)

def coordinates():
    liste5.clear()
    tagliler=canvas.find_withtag('kirmizi')
    liste5.extend(tagliler)
    liste6.clear()
    for i in liste5:
        liste6.extend(canvas.coords(i))
    output = []
    for i in range(len(liste6)-2):
        output.append((liste6[i] + liste6[i + 2])/2)
    print(output)

b1=tkinter.Button(canvas,text="stop",command=coordinates)
b1.place(x=900,y=200)
canvas.pack()
top.mainloop()
if __name__ == '__main__':
    try:
        from tkinter import *
    except ImportError:
        from Tkinter import *

Stop button runs the function.停止按钮运行该功能。 Let me explain what is wrong with it with numbers.让我解释一下数字有什么问题。 When object 1 is selected the coordinates are true.选择对象1时,坐标是真的。 For example when I choose only object 1, I get :例如,当我只选择对象 1 时,我得到:

[25.0,25.0]

And when I choose only object 2, I get:当我只选择对象 2 时,我得到:

[40.0,75.0]

But when I choose both of these objects together, I get:但是当我同时选择这两个对象时,我得到:

[25.0, 25.0, 32.5, 50.0, 40.0, 75.0]

As you can see there are unnecessary values.如您所见,存在不必要的值。 I want to get 2 values from each object, any help would be appreciated.我想从每个对象中获取 2 个值,任何帮助将不胜感激。

You should calculate the center x, y for every 4 items in liste6 :您应该为liste6每 4 个项目liste6 x, y :

for i in range(0, len(liste6), 4):
    output.append((liste6[i] + liste6[i+2])/2) # center x
    output.append((liste6[i+1] + liste6[i+3])/2) # center y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM