用户界面- Python tkinter find_overlap元组



python tkinter Canvas中的'find_overlap '函数返回是什么?

from tkinter import *
a = Tk()
table = Canvas(a, width=500, height=300, bg='white')
table.pack()
my_oval = table.create_oval(40, 40, 80, 80)
c_object = table.find_overlapping(30, 30, 70, 70)
print(c_object)
a.mainloop()
>>> (1, )

返回一个元组到控制台。我想要的是给my_oval分配一个ID,而不是返回一个元组,我希望返回ID。

my_oval.[some_kind_of_id] = 'myID'
c_object = table.find_overlapping(30, 30, 70, 70)
print(c_object)
>>> (1, )
# I want 'myID' to be printed

*注意:上面的代码将返回一个语法错误,因为我的[some_kind_of_id]分配。我想要的三点:

1)为形状指定某种ID

2) find_overlap of a point

3)如果形状与点重叠,则返回形状的ID

编辑:为了明确我想要什么,我正在制作一款tkinter游戏,如果我的方块碰到墙壁,它就会停止,但如果它碰到硬币,它就会继续前进。因此,如果正方形返回的id(通过内置函数'find_overlap ')属于墙,则正方形将停止。

我对画布不太熟悉,但看起来find_overlapping正在为您正在创建的每个椭圆形返回一个ID,从1开始并递增1。实际上,如果您打印椭圆形对象:

print(my_oval)

返回1。如果你有一秒钟的时间来打印它,它将是2。

所以,这就变成了一个跟踪每个椭圆的对象id的问题。考虑一个包含所有id的字典;当你创建一个椭圆时,你给它一个id并把它插入字典。然后,创建一个函数(overlaps()),返回匹配重叠值的所有键的列表。

看一下这个工作示例,如果有什么不合理的地方告诉我:

from tkinter import *
def overlaps((x1, y1, x2, y2)):
    '''returns overlapping object ids in ovals dict'''
    oval_list = [] # make a list to hold overlap objects
    c_object = table.find_overlapping(x1, y1, x2, y2)
    for k,v in ovals.items():  # iterate over ovals dict
        if v in c_object:      # if the value of a key is in the overlap tuple
            oval_list.append(k)# add the key to the list
    return oval_list
a = Tk()
# make a dictionary to hold object ids
ovals = {}
table = Canvas(a, width=500, height=300, bg='white')
table.pack()
# create oval_a and assign a name for it as a key and
# a reference to it as a value in the ovals dict.
# the key can be whatever you want to call it
# create the other ovals as well, adding each to the dict
# after it's made
oval_a = table.create_oval(40, 40, 80, 80)
ovals['oval_a'] = oval_a
oval_b = table.create_oval(60, 60, 120, 120)
ovals['oval_b'] = oval_b
oval_c = table.create_oval(120, 120, 140, 140)
ovals['oval_c'] = oval_c
# draw a rectangle
rectangle = table.create_rectangle(30, 30, 70, 70)
# print the return value of the overlaps function
# using the coords of the rectangle as a bounding box
print(overlaps(table.coords(rectangle)))
a.mainloop()

相关内容

  • 没有找到相关文章

最新更新