访问添加到 Tkinter 根的对象 [英] Accessing objects added to the Tkinter root

查看:28
本文介绍了访问添加到 Tkinter 根的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

root = Tk()
open = Button(self.root, text='Open', command=self.open, state='disabled')
open.pack()
close = Button(self.root, text='Close', command=self.close, state='disabled')
close.pack()

我只想在执行某些操作时启用按钮,因此我需要稍后再次访问按钮以编辑状态变量.不是将按钮添加到单独的列表并存储它,而是有一种方法可以访问按钮,或者就此而言,我附加到根的任何对象集(菜单、下拉列表或其他),通过在根上调用方法?

I only want to enable the buttons when some action is performed, so I need to access the buttons again later to edit the state variable. Rather than adding the buttons to a separate list and storing that, is there a way of accessing the buttons, or, for that matter, any set of objects that I have attached to the root (Menus, Drop down lists, or whatever), by calling a method on the root?

推荐答案

没有确定的方法可以向根窗口询问所有小部件的列表.您可以使用 pack_slavesgrid_slaves 来获取由特定容器管理的小部件列表,但取决于您编写应用程序的方式,这并不能保证您将获得所有小部件.

There is no definitive way to ask the root window for a list of all widgets. You can use pack_slaves or grid_slaves to get a list of widgets managed by a particular container, but depending on how you write your app that's no guarantee you'll get all the widgets.

您还可以使用 winfo_children 获取小部件的所有直接后代的列表.如果您有一个嵌套的小部件层次结构(例如,为了组织目的而使用框架作为中间容器),您可能需要进行某种循环才能找到特定的小部件.

You can also use winfo_children to get a list of all direct descendants of a widget. If you have a nested hierarchy of widgets (for example, by using frames as intermediary containers for organizational purpose) you may have to do some sort of looping to find a particular widget.

最好和最简单的方法是让您的应用程序成为类的实例.然后,您可以将小部件的引用保存为类的属性.我强烈推荐这种方法,没有充分的理由以任何其他方式来做.

The best and simplest approach is to have your application be an instance of a class. You can then save references to the widgets as attributes of the class. I highly recommend this approach, there's simply no good reason to do it any other way.

例如:

class MyApp(Tk):
    def __init__(self, *args, **kwargs):
        ...
        self.open_button = Button(...)
        self.close_button = Button(...)
        ...
    def OnSomeEvent(self, event):
        if ...:
            self.open_button.configure(state="disabled")
        else:
            self.open_button.configure(state="normal")

这篇关于访问添加到 Tkinter 根的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆