2013-07-26 39 views
-2

使用tkinter,當我嘗試打開客戶端,我得到了錯誤:NameError:全球名「客戶」沒有定義

NameError: global name 'client' is not defined

Traceback(most recent call lost): 
File "C:\Users\Gerardi\Desktop\graf2.py", line 21, in <module> 
cliente2 = conectar() 
File "C:\Users\Gerardi\Desktop\graf2.py", line 18, in conectar 
cliente.connect(address) 
File "C:\Python27\lib\socket.py", line 224, in meth 
return getattr(self._sock,name)(*args) 
ocket.error: [Errno 10049] La direcci¾n solicitada no es vßlida en este context 

def conectar(): 
    cliente = socket.socket(2,1) 
    ip = cuadro_texto3.get("1.0", "1.end") 
    address = (ip, 5001) 
    cliente.connect(address) 
    return cliente 

cliente2 = conectar() 

def check_message(cliente): 
while True: 
    try: 
     datos = cliente.recv(1000) 
     cuadro_texto2.insert("1.0", datos) 
    except socket.error: 
     break 
    if datos == "quit": 
     cliente.close() 
     server.close()  
cliente.close() 
+0

錯誤狀態表明您正嘗試使用未定義的變量'cliente'。也許你拼錯了它,也許你在使用它之前沒有初始化它......如果你需要更多的幫助,請顯示'check_message'的源碼 – Gryphius

+0

你應該編輯這個問題來添加代碼,在這裏它是不可讀的。 –

+0

我真的很抱歉,這是我的第一個問題.. –

回答

1

,則不應使用全球反正。使用返回值和參數。

def conectar(): 
    [... your code ...] 
    return cliente 

def check_message(cliente): 
    [... your code ...] 

client = conectar() 
check_message(client) 

此外,在名爲* check_message *的函數中關閉連接可能不是一個好主意。你應該有一個自己的功能。

從長遠來看,重構類中的整個代碼可能是一個好主意。

相關問題