亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

tkinter 類對象未定義

tkinter 類對象未定義

夢里花落0921 2023-10-05 16:45:02
我對 Python 相當陌生,這是我使用 tkinter 的第一個項目。我的整個項目運行良好,只有一個例外。我已將 tkinter 代碼構建到一個類中,一切正常,但我不知道如何從類外部調用這些方法。當我在 main 中的以下行創建對象時,出現 NameError: name 'robotGUI' is not Definedclass botGUI:    def __init__(self):        #Init Code    def updateStatus(self):        #Code HererobotGUI = botGUI()如果我將變量“robotGUI”初始化為 None,代碼就會運行,但是當我稍后嘗試訪問其方法之一時,我會收到 AttributeError: 'NoneType' object has no attribute 'doSomething'。似乎沒有創建 robotsGUI 對象,但我不明白為什么。我到處搜索并找到了一些接近的答案,但沒有任何與這個問題完全相關的答案。我有一些其他類在這個程序中運行得很好,所以我確信它與 tkinter 和它的內部主循環有關,只是無法確定它。這是我大大減少和簡化的代碼,顯示了問題:#!/usr/bin/env python3#Importsimport socket, select, errno, sys, queue, time, threading, cv2from tkinter import *from tkinter import fontfrom PIL import Image, ImageTk#GUIclass botGUI:    def __init__(self):        #Create the Window Object and Setup the Window        self.window = Tk()        self.window.geometry("800x480+0+0")        self.window.overrideredirect(True)        self.window.fullScreenState = False        #Code to Generate Gaphics Here .....                #Call Repeating Status Update Script and Start the Main Loop        self.updateStatus()        self.window.mainloop()        def updateStatus(self):        #Code to Handle Updating Screen Objects Here ....            print("Update Status Running")        #Set this function to be called again        self.window.after(1000, lambda: self.updateStatus())            def doSomething(self, myStr):        #Code to change something on the screen ...        print(f"Command: {str(myStr)}")    def doSomethingElse(self, myStr):        #Code to change something on the screen ...        print(f"Command: {str(myStr)}")        
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

self.window.mainloop()刪除的呼叫botGUI.__init__(),然后您可以:

  • 創建以下實例botGUIrobotGUI = botGUI()

  • 創建線程并啟動它

  • 稱呼roboGUI.window.mainloop()

下面是修改后的代碼:

#!/usr/bin/env python3


#Imports

import socket, select, errno, sys, queue, time, threading, cv2

from tkinter import *

from tkinter import font

from PIL import Image, ImageTk


#GUI

class botGUI:


    def __init__(self):


        #Create the Window Object and Setup the Window

        self.window = Tk()

        self.window.geometry("800x480+0+0")

        self.window.overrideredirect(True)

        self.window.fullScreenState = False


        #Code to Generate Gaphics Here .....        


        #Call Repeating Status Update Script and Start the Main Loop

        self.updateStatus()

        #self.window.mainloop()    


    def updateStatus(self):


        #Code to Handle Updating Screen Objects Here ....    

        print("Update Status Running")


        #Set this function to be called again

        self.window.after(1000, lambda: self.updateStatus())

        


    def doSomething(self, myStr):


        #Code to change something on the screen ...

        print(f"Command: {str(myStr)}")


    def doSomethingElse(self, myStr):


        #Code to change something on the screen ...

        print(f"Command: {str(myStr)}")

        



#Main Task - Since tKinter is running in the main loop, all of the main loop code is moved to here

def main_loop():


    #global robotGUI

    robotDataReceived = True #This is only for this posting


    #Main Loop

    while True:


        #If Incoming Data from Robot, Get and Process It!

        if robotDataReceived:

            robotCmdHandler()

            

        #Anti Blocking Delay (Much shorter, set higher for this post)

        time.sleep(2)



#Robot Command Handler

def robotCmdHandler():


    #global robotGUI


    #Code to get a command string and process it goes here .....

    cmd = "dosomething"  #Temporary for this post


    #Handle command

    if (cmd == "dosomething"):

        print("Processing Command")

        robotGUI.doSomething("Do This")



if __name__ == '__main__':


    #Create GUI Object

    robotGUI = botGUI()


    #Create and Start Threads

    t1 = threading.Thread(target=main_loop, name='t1')

    t1.start()            


    # start the GUI main loop

    robotGUI.window.mainloop()


    #Wait until threads are finished

    t1.join()


查看完整回答
反對 回復 2023-10-05
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

您必須在所有函數之外定義 robotsGUI,如下所示:


robotGUI = None

def main_loop():


     global robotGUI

     robotDataReceived = True #This is only for this posting


     #Main Loop

     while True:


         #If Incoming Data from Robot, Get and Process It!

         if robotDataReceived:

             robotCmdHandler()

        

         #Anti Blocking Delay (Much shorter, set higher for this post)

         time.sleep(2)


查看完整回答
反對 回復 2023-10-05
  • 2 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號