【问题标题】:How can I access or configure Tkinter widget attribute from a separated class in python?如何从 python 中的单独类访问或配置 Tkinter 小部件属性?
【发布时间】:2017-04-20 02:02:18
【问题描述】:

我想用 Python 和 Tkinter 制作一个简单的 GUI 程序。 我下载了winPython 并将其python3.5.2 目录提取为我的python 环境。

然后,我使用了this thread 中提供的SpecTcl GUI builder。 我用这个构建器构建了一个简单的 GUI,GUI 只包含一个按钮和一个文本区域。生成器生成2个python文件,一个是“SimpleGUI_ui.py”,另一个是“SimpleGUI.py”。我将两个.py 文件放入python3.5.2 目录并运行python3.5.2.exe SimpleGUI.py 以显示GUI。

下面是SimpleGUI.py 代码。省略了一些不是很重要的代码。

""" simpleGUI.py --
UI generated by GUI Builder Build 146 on 2016-12-05 22:47:05 from:
C:/Users/User/Downloads/guimaker/simpleGUI.ui
 This file is auto-generated.  Only the code within
'# BEGIN USER CODE (global|class)'
'# END USER CODE (global|class)'
and code inside the callback subroutines will be round-tripped.
The 'main' function is reserved.
"""
from tkinter import *
from simpleGUI_ui import SimpleGUIcd
# BEGIN USER CODE global
# END USER CODE global
class CustomSimpleGUI(SimpleGUI):
    pass

    # BEGIN CALLBACK CODE
    # ONLY EDIT CODE INSIDE THE def FUNCTIONS.
    # _button_1_command --
    # Callback to handle _button_1 widget option -command
    def _button_1_command(self, *args):
        SimpleGUI._text_1.config(text="hello world") # This is useless

    # _text_1_xscrollcommand --
    # Callback to handle _text_1 widget option -xscrollcommand
    def _text_1_xscrollcommand(self, *args):
        pass
    # I omit another yScrollCommand here.

def main():
    # Standalone Code Initialization, DO NOT EDIT
    try: userinit()
    except NameError: pass
    root = Tk()
    demo = CustomSimpleGUI(root)
    root.title('simpleGUI')
    try: run()
    except NameError: pass
    root.protocol('WM_DELETE_WINDOW', root.quit)
    root.mainloop()
if __name__ == '__main__': main()

下面是SimpleGUI_ui.py代码:

""" simpleGUI_ui.py --
UI generated by GUI Builder Build 146 on 2016-12-05 22:47:05 from:
C:/Users/User/Downloads/guimaker/simpleGUI.ui
THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE EDITED.
The associated callback file should be modified instead.
"""
import tkinter
import os # needed for relative image paths
class SimpleGUI(object):
    _images = [] # Holds image refs to prevent GC
    def __init__(self, root):
        # Widget Initialization
        self._button_1 = tkinter.Button(root,
            text = "_button_1",
        )
        self._text_1 = tkinter.Text(root,
            height = 0,
            width = 0,
        )
        # widget commands
        self._button_1.configure(
            command = self._button_1_command
        )
        self._text_1.configure(
            xscrollcommand = self._text_1_xscrollcommand
        )
        self._text_1.configure(
            yscrollcommand = self._text_1_yscrollcommand
        )
        # Geometry Management
        self._button_1.grid(
            in_    = root,
            column = 1,
            row    = 1,
            columnspan = 1,
            ipadx = 0,
            ipady = 0,
            padx = 0,
            pady = 0,
            rowspan = 1,
            sticky = ""
        )
        self._text_1.grid(
            in_    = root,
            column = 1,
            row    = 2,
            columnspan = 1,
            ipadx = 0,
            ipady = 0,
            padx = 0,
            pady = 0,
            rowspan = 1,
            sticky = "news"
        )
        # Resize Behavior
        root.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
        root.grid_rowconfigure(2, weight = 0, minsize = 40, pad = 0)
        root.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
        root.grid_columnconfigure(2, weight = 0, minsize = 40, pad = 0)

所以我遵循了它的评论:修改回调,但不修改 _ui 代码。

现在我遇到的问题是我什至无法简单地更改 _text_1 小部件中的文本。我试过打电话SimpleGUI._text_1.config(text="hello world"),但是当我点击GUI上的按钮时它给了我下面的异常:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\User\Downloads\python-3.5.2\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "simpleGUI.py", line 29, in _button_1_command
    SimpleGUI._text_1.config(text="hello world")
AttributeError: type object 'SimpleGUI' has no attribute '_text_1'

谁能帮助我,我如何接受_text_1 小部件并在回调函数中配置其文本,以便我可以使我的 GUI 交互,希望我可以使用相同的方式访问和控制任何其他小部件图形用户界面。谢谢!

【问题讨论】:

  • 以下划线开头的标识符是私有的,不能在类外访问。您需要创建根据需要修改它们的方法,并从其他类中调用这些方法。
  • 嗨@DYZ 感谢您的回复,那么您的意思是,如果不对SimpleGUI_ui.py 进行任何修改,就无法访​​问GUI 小部件?即使代码中的注释说 SimpleGUI_ui.py 不应该被编辑。

标签: python tkinter python-3.5


【解决方案1】:

很遗憾,如果不修改SimpleGUI_ui.py 代码,我就找不到访问小部件的方法。 @DYZ 是对的,我在SimpleGUI_ui.pySimpleGUI.py 的回调函数中添加了一个函数 我调用了该函数,将self 作为第一个参数传递,然后成功 访问了小部件。

SimpleGUI_ui.py:

class MailLogChecker(object):
    # other code omitted
    def foo(self):
        self._text_1.insert(1.0, 'abc')

SimpleGUI.py:

class CustomSimpleGUI(SimpleGUI):
    # other code omitted
    def _button_1_command(self, *args):
        # call like this and pass self to access widgets in UI
        SimpleGUI.foo(self)

我仍在寻找一种仅更改 SimpleGUI.py 就足以访问 UI 小部件的方法。 无论如何,感谢@DYZ 给我提示。

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2016-02-08
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多