在python画布中,“find_overlapping”函数返回什么?
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_overlapping
3)如果形状与点重叠,则返回形状的ID
编辑:为了弄清楚我想要什么,我正在用平纹机做一个游戏,如果我的方格碰到一堵墙,它就会停下来,但是如果它碰到一个硬币,它就会继续前进。因此,如果由正方形返回的id (内置函数'find_overlapping')属于墙,则广场将停止。
发布于 2014-05-06 00:13:30
我对画布不太熟悉,但看起来find_overlapping正在为您创建的每个椭圆返回一个ID,从1开始递增。实际上,如果您打印了oval对象:
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()https://stackoverflow.com/questions/23479672
复制相似问题