Getting the parent of a parent widget in Python Tkinter

女生的网名这么多〃 提交于 2019-12-24 03:39:14

问题


I am trying to get the parent of a widget then get the parent of that widget. But Everytime I try to I get a error.

Error:

AttributeError: 'str' object has no attribute '_nametowidget'

Why is it giving me that error. Can someone explain to me why I am getting this error and help me to fix it?

Code:

parent = event.widget.winfo_parent()
parentName = event.widget._nametowidget(parent)

frameParent = parentName.winfo_parent()
frameParentName = frameParent._nametowidget(frameParent)

回答1:


http://effbot.org/tkinterbook/widget.htm

Mentions as below, winfo_parent() is a method to get parent's name.

The error you get means that event.widget doesn't has the method named _nametowidget. So you could not call that as a function.

You may try codes below to get the parent.

parent = event.widget.winfo_parent()
from Tkinter import Widget
Widget._nametowidget(parent)



回答2:


grandparent = event.widget.master.master

See the answer here.




回答3:


Your second call to _nametowidget() is different than your first. Your fourth line is bad, since you're basing the call to _nametowidget() on a string (frameParent) instead of on a widget (parentName). This is partly because your naming convention of "widget" and "widgetName" is reversed...

frameParentName = frameParent._nametowidget(frameParent)

                   ^^^^^^^^^^^ -- this is the name string. you need a widget

I would slightly rewrite your code as follows:

parentName = event.widget.winfo_parent()
parent     = event.widget._nametowidget(parentName) #event.widget is your widget

frameParentName = parent.winfo_parent()
frameParent     = parent._nametowidget(frameParentName) #parent is your widget


来源:https://stackoverflow.com/questions/27161734/getting-the-parent-of-a-parent-widget-in-python-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!