【发布时间】:2020-12-19 13:48:22
【问题描述】:
我在 python 中实现了以下代码来操作按下按钮的自己的属性(此处为 button.text)。 执行代码时出现以下错误:“AttributeError: 'Gui' object has no attribute 'button'”。对于我的示例来说重要的是,该按钮是类的一部分,并在其 init 中创建。我找到并运行的其他带有全局定义按钮的工作示例。
#!/usr/bin/python3
# -*- coding: iso-8859-1 -*-
import tkinter
from tkinter import *
from tkinter import ttk
class Gui:
def __init__(self, master):
self.master = master
self.frame = Frame(self.master)
self.frame.pack(fill='both', side='top', expand='True')
self.button = Button(master=self.frame,
text='connect',
height=20,
width=80,
padx=1,
pady=1,
command=self.connect_disconnct(),
compound=LEFT)
self.button.grid(row=0, column=0, padx=5, pady=5, sticky='ew')
mainloop()
def connect_disconnct(self):
if self.button.test == connect:
print("Button pressed -> connect")
self.button.text = "disconnect"
else:
print("Button pressed -> disconnect")
self.button.text = "connect"
if __name__ == '__main__':
form = Tk()
Gui(form)
form.mainloop()
如何将自己的按钮元素传递给回调函数,例如可以在回调函数中更改调用对象的文本?
【问题讨论】:
标签: python python-3.x button tkinter callback