更改按钮上的小部件,按Tkinter(Python)

时间:2018-07-27 08:00:55

标签: python tkinter

我正在编写一个GUI的代码,该GUI使用Label显示一些文本,并且在按下按钮时,我想更改Label的文本。 这是我制作小部件的代码。

def makeWidget(self):
    self.widgets = []
    widget1 = Label(self, width=50, height=20)
    widget1.config(text='There is going to be smth here!')
    widget1.pack(side=TOP, fill=BOTH)
    self.widgets.append(widget1)

我正在__init__(self, parent=None)中调用此函数。一切都很好。但是,当我按下要为其分配update

命令的按钮时
def update(self):
    self.widgets[0].config(text='Here text should change')

Error出现

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python37-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:/Users/User/PycharmProjects/untitled4/venv/main.py", line 17, in 
<lambda>
toolBar = [('Edit', lambda :(makeGui.update(root)), {'side': 'left'}),
File "C:\Users\User\PycharmProjects\untitled4\venv\Include\menu_toolbar.py", 
line 71, in update
self.widgets[0].config(text='Here text should change')
File "C:\Python37-32\lib\tkinter\__init__.py", line 2098, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'widgets'  

我最初认为rpoblem是因为self.widget未被保存在任何地方,这就是为什么self.widgets=[]试图保存它的原因 有人可以帮忙吗?如何通过按按钮在窗口小部件中进行更改。

P.S如果问题不在我上面提到的地方,那么这里是我的完整代码:


这是我的main.py

from tkinter import *
from Include.menu_toolbar import makeGui
import time
root=Tk()
menuBar = [
    ('File', 0,
     [('Open', 0, lambda: 0),
      ('Quit', 0, sys.exit)]),
    ('Edit', 0,
     [('Add', 0, lambda: 0),
      ('Remove', 0, lambda: 0)]),
    ('Help', 0,
     [('About', 0, lambda: 0),
      ('Optins', 0, lambda: 0)])
    ]
toolBar = [('Edit', lambda :(makeGui.update(root)), {'side': 'left'}),
               ('Add', lambda: 0, {'side': 'left'}),
               ('Remove', lambda: 0, {'side': 'left'})
               ]

toolbarColor = '#3C3F41'
class LocalGuiMaker(makeGui):
    def start(self):
        self.menuBar = menuBar
        self.toolBar = toolBar
        self.toolbarColor = toolbarColor
LocalGuiMaker(root).mainloop()

这是我的menu_toolbar.py

from tkinter import * 
import sys, time

class makeGui(Frame):
    menuBar = []
    toolBar = []
    toolbarColor = 'white'
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        self.start()
        self.makeMenuBar()
        self.makeToolBar()
        self.makeWidget()
    def makeMenuBar(self):
        menubar = Menu(self.master)
        self.master.config(menu=menubar)
        for (name, u_index, items) in self.menuBar:
            pulldown = Menu(menubar)
            self.addItems(pulldown, items)
            menubar.add_cascade(label=name, underline=u_index, menu=pulldown)

    def addItems(self, menu, items):
        for item in items:
            if item == 'separator':
                menu.add_separator({})
            elif type(item[2]) != list:
                menu.add_command(label=item[0],
                             underline=item[1],
                               command=item[2])
            else:
                pullover = Menu(menu)
                addItem(pullover, item[2])
                menu.add_cascade(label=item[0],
                               underline=item[1],
                               menu=pullover)

    def makeToolBar(self):
        toolbar = Frame(self, relief=SUNKEN, bd=2, bg=self.toolbarColor)
        toolbar.pack(side=BOTTOM, fill=X)
        for (name, command, place) in self.toolBar:
            Button(toolbar, text=name, command=command, fg='white', 
                    bg=self.toolbarColor).pack(place)
        clock = Label(toolbar, fg='white', bg=self.toolbarColor)
        clock.pack(side=RIGHT, expand=False, fill=Y)
        time1 = ''

        def tick():
            nonlocal time1
            time2 = time.strftime('%H:%M:%S')
            if time2 != time1:
                time1 = time2
                clock.config(text=time1)
            clock.after(200, tick)

        tick()


    def makeWidget(self):
        self.widgets = []
        widget1 = Label(self, width=50, height=20)
        widget1.config(text='There is going to be smth here!')
        widget1.pack(side=TOP, fill=BOTH)
        self.widgets.append(widget1)

    def update(self):
        self.widgets[0].config(text='Here text should change')


    def start(self):
        pass

1 个答案:

答案 0 :(得分:0)

问题出在工具栏的创建上

toolBar = [('Edit', lambda :(makeGui.update(root)), {'side': 'left'}),
               ('Add', lambda: 0, {'side': 'left'}),
               ('Remove', lambda: 0, {'side': 'left'})
               ]

特别是makeGui.update(root)

您希望按钮执行的操作是调用您创建的update实例的makeGui方法,但是您正在执行的操作是调用{{1 }}类。问题在于您目前无法引用update实例,因为它尚不存在。

是否有必要在makeGui类之外定义makeGuimenuBartoolBar?它已经是toolbarColor类周围的简单包装了吗?如果在LocalGuiMaker函数中定义它们,则可以使用makeGui来引用类实例:

start