简体   繁体   English

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

[英]Changing the widget on button press Tkinter (Python)

I am writing the code for a GUI that displays some text with Label and on button press, I want to change the text of my Label. 我正在编写GUI的代码,该GUI使用Label显示一些文本,并且在按下按钮时,我想更改Label的文本。 Here is my code for making a widget. 这是我制作小部件的代码。

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)

I am calling this function in my __init__(self, parent=None) . 我在我的__init__(self, parent=None)调用此函数。 And everything is working nice. 一切都很好。 But when I am pressing the button for which I am assigning the command of update 但是当我按下要为其分配update命令的按钮时

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

the Error is appearing 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'  

I initial thought that the rpoblem is becouse self.widget is not being saved in anywhere that is why tried to save it by self.widgets=[] Can someone help? 我最初认为rpoblem是self.widget没有保存在任何地方,所以为什么尝试通过self.widgets=[]来保存它。有人可以帮忙吗? How can I make changes in my widget with button press. 如何通过按按钮在窗口小部件中进行更改。

PS In case the problem is not in the places I have mentioned above, here is my full code: 附注:如果问题不在我上面提到的地方,请使用以下完整代码:


This is my main.py : 这是我的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()

This is my menu_toolbar.py : 这是我的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

The problem's in the creation of the toolbar 问题出在工具栏的创建上

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

And specifically makeGui.update(root) . 特别是makeGui.update(root)

What you want the button to do is call the update method of the makeGui instance you create, but what you're doing is calling the update method on the makeGui class. 您希望按钮执行的操作是调用您创建的makeGui实例的update方法,但是您正在执行的操作是调用makeGui类的update方法。 The problem is you can't reference the makeGui instance at this point, since it doesn't exist yet. 问题在于您目前无法引用makeGui实例,因为它尚不存在。

Is there any reason for defining menuBar , toolBar and toolbarColor outside of the LocalGuiMaker class? 是否有toolbarColorLocalGuiMaker类之外定义menuBartoolBartoolbarColor It's already a simple wrapper around the makeGui class right? 已经是makeGui类的简单包装了,对吗? If you define them inside the start function, you can reference the class instance by using self : 如果在start函数中定义它们,则可以使用self 引用类实例:

class LocalGuiMaker(makeGui):
    def start(self):
        self.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)])
                       ]
        self.toolBar = [
                       ('Edit', self.update, {'side': 'left'}),
                       ('Add', lambda: 0, {'side': 'left'}),
                       ('Remove', lambda: 0, {'side': 'left'})
                       ]

        self.toolbarColor = '#3C3F41'

LocalGuiMaker(root).mainloop()

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

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