简体   繁体   English

Tkinter - 如何通过单击矩形获取标签名称

[英]Tkinter - How To Get Tag Name from Clicking on Rectangle

I'm fairly new to programming, so appoloigise for any inconsistencies / using code incorrectly)我对编程相当陌生,因此请注意任何不一致/错误使用代码)

I've seen a few similar questions and answers on this topic, however I feel like I may be missing something.我在这个主题上看到了一些类似的问题和答案,但是我觉得我可能遗漏了一些东西。

I've drawn a net of a Rubiks Cube, and I want the user to be able to click on an individual 'cubie' to change its colour, so it will filter through the 6 colours.我画了一个魔方网,我希望用户能够点击一个单独的“魔方”来改变它的颜色,所以它会过滤 6 种颜色。 Basically, what I'm trying to figure out is how to access the tag of the rectangle, from the tag_bind method.基本上,我想弄清楚的是如何从 tag_bind 方法访问矩形的标签。

Here is a simplified version of the code I have used:这是我使用的代码的简化版本:

def clicked(event):
    print("You clicked " + str(event))
    print(event.widget.find_withtag("current"))


green_00 = cubeCanvas.create_rectangle(20, 240, 90, 310, width=0, fill='green', tag="green_00")
cubeCanvas.tag_bind("green_00", "<Button-1>", clicked)

This currently returns:这当前返回:

You clicked <ButtonPress event num=1 x=56 y=299>
(1,)

Whereas ideally I want it to return:而理想情况下我希望它返回:

green_00

The aim would then be to use the tag, to identify the rectangle in itemconfig - so that I can change the colour.然后,目标是使用标签来识别 itemconfig 中的矩形 - 这样我就可以更改颜色。 Any answer / a better way to approach this problem is greatly appreciated.非常感谢任何解决此问题的答案/更好的方法。

Thanks.谢谢。

Thanks to Atlas435 - I was missing something very small.感谢 Atlas435 - 我错过了一些非常小的东西。

current = event.widget.find_withtag("current")[0]
event.widget.itemconfig(current, *option)

Allows you to access and then change the colour of the specific tag.允许您访问然后更改特定标签的颜色。

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

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