2014-01-31 83 views
0

我很难从另一个python脚本中的一个函数传递变量到另一个函数。我已阅读其他答案,但他们并没有真正帮助这个问题。将变量传递给另一个Python脚本

这是第一个文件欲变量发送至(为清楚起见省略了一些代码)

# TestGUI.py 

from Tkinter import * 
import serial 
import os 

class Testgui: 
    def __init__(self, master): 

    def writetoBOT(self,instruct): 
     ser = serial.Serial(6) 
     ser.baudrate = 9600 
     ser.parity = serial.PARITY_NONE #set parity check: no parity 
     ser.timeout = 1   #non-block read 
     ser.writeTimeout = 2  #timeout for writ 

     if(ser.isOpen() == False): 
      ser.open() 
      print ser.portstr  # check which port was really used 
      ser.write(instruct) 
     else : 
      ser.write(instruct) 

这是sceond文件:

# TestGUI_2.py 

from TestGUI import Testgui 

class Tracker: 
    def __init__(self): 
     pass 
    def drive(self,cords, cords1): 
     while(cords >= 320):   
      l='l' 
      Testgui.writetoBOT(l)  # This is the problem line 

类型错误:未结合的方法writetoBOT()必须使用TestGUI实例作为第一个参数调用(代替str实例)

+0

你有2个文件,但你正在尝试执行*一个*脚本,对吧?你的描述很混乱。 –

回答

4

writetoBOT需要2个参数:selfinstruct。 与Testgui实例调用它:

tgui=Testgui(your_master) 
tgui.writetoBOT(l) 

如果你想与Testgui类来调用它,你仍然需要通过的Testgui一个实例:

tgui=Testgui(your_master) 
Testgui.writetoBOT(tgui, l) 
+0

(your_master)是调用类吗?在这种情况下Tracker()? –

+0

@ user3257360这是构建Testgui实例时需要传递的参数。参见'def __init __(self,master)'。你不是写这段代码的吗? – zhangxaochen

+0

为了修复我的代码,我创建了另一个名为writetoSerial()的类,并在其中放入了串行编写代码。然后导入函数,然后调用它:从TestGUI_2导入writetoSerial然后调用函数:l ='l' t = writetoSerial() t.writetoBOT(l) –

0

或者,您也可以让普通的空间这两个脚本,它通过ACN数据库 - sqllite

例如,

# file1.py 
import sqlite3 

con = sqlite3.connect('messages.db') 
cur = con.cursor() 
#cur.execute('CREATE TABLE message (id INTEGER PRIMARY KEY, name TEXT, content TEXT, read INTEGER)') 
#con.commit() 


for x in range(100000): 
    if x in range(1, 500): 
     cur.execute('INSERT INTO message (id, name, content, read) VALUES(NULL, "Guido", "van Rossum", 0)') 
     con.commit() 

# file2.py 
import sqlite3 
import time 

con = sqlite3.connect('messages.db') 
cur = con.cursor() 

def listen(): 
    messages = cur.execute('SELECT * FROM message WHERE read=0') 
    if not messages: 
     return False 
    for m in messages: 
     print 'get message ', m 
     cur.execute("UPDATE message SET read=1 WHERE id=?", m[0])   
     con.commit() 
     print 'update db' 
    return True 

while True: 
    listen() 
    time.sleep(5) 
0

您声明为Testgui作为一个类。这应该被理解为骨架或线框(注意,这是一条捷径,而不是现实)。您需要首先从该骨架中创建一个“真实”对象才能使用它。

testgui=Testgui(amaster) 

在类中可能有在类级应用的方法(绑定函数)。这些被称为静态方法或类方法。他们必须用蟒蛇装饰。

查看http://en.wikipedia.org/wiki/Object_oriented_programming了解更多信息。

相关问题