【问题标题】:AttributeError: 'function' object has no attribute 'addNewMessage'AttributeError:“函数”对象没有属性“addNewMessage”
【发布时间】:2019-05-10 15:31:54
【问题描述】:

我正面临这个问题。我对 py 中的线程和 GUI 都很陌生,这就是为什么我无法摆脱它。 基本上我有这个类:

class receiving(threading.Thread): #thread class
    #init and other methods
    def run(self):
    data = self.sock.recv(1024) #sock is the socket on which the 'run' method as to listen on
    UserIF.main.addNewMessage(data) #with this line i want to pass the 'data' variable to the 'addNewMessage' method

侦听套接字并返回一个字符串,我必须将此字符串写入此类中的 tkinter 'Text' 对象:

class UserIF():
    def main(self):
        #some code
        messages = tk.Text(master=window, height=10, width=30)
        messages.grid(column=5, row=4)
        def addNewMessage(string):
            messages.insert(string)

我正在尝试一种我知道在 python 中不存在的“转到”。

【问题讨论】:

  • 您没有将self 作为def addNewMessage(string): 中的参数传递,但我不相信您需要嵌套函数。 tkinter 对我来说不是强项。
  • @roganjosh 这不是 tkinter 真正的问题,这是我如何将线程类的 run 方法中的“数据”变量传递给 UserIF 类的 main 方法来打印它让我们说.

标签: python class user-interface methods tkinter


【解决方案1】:

为什么还要使用嵌套函数?只需在与main 函数相同的标识上创建addNewMessage 函数,不要忘记在string 之前添加self 默认参数。然后run 函数中的UserIF.addNewMessage(data) 应该可以工作。

class receiving(threading.Thread): #thread class
    #init and other methods
    def run(self):
        data = self.sock.recv(1024)
        UserIF.addNewMessage(data)

class UserIF():
    def main(self):
        #some code
        self.messages = tk.Text(master=window, height=10, width=30)
        self.messages.grid(column=5, row=4)

    def addNewMessage(self, string):
        self.messages.insert(string)

如果您不需要使用self,您也可以创建一个静态方法。

@staticmethod
def addNewMessage(string):
    #The next two lines I'm not sure if they are needed.
    messages = tk.Text(master=window, height=10, width=30)
    messages.grid(column=5, row=4)
    #This should work now
    messages.insert(string)

【讨论】:

  • 但是'messages'文本字段不会在'window'框架内,因为它是在main方法中初始化的
  • 它显然说:“未解决对‘窗口’的引用”
  • 然后只需将窗口对象传递给 addNewMessage 函数,您可以将其转换为我猜的类变量,请参阅我的编辑。没有看到整个代码就无法猜测更多。
猜你喜欢
  • 2022-01-14
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 2017-03-05
  • 1970-01-01
相关资源
最近更新 更多