首页 文章

AttributeError:'function'对象没有属性'addNewMessage'

提问于
浏览
0

我正面临着这个问题 . 我在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)

我正在尝试一种'go to',我知道在python中不存在 .

1 回答

  • 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)
    

相关问题