在python中调用模块中的线程

时间:2014-09-02 19:27:51

标签: python multithreading import module

我有一个登录屏幕,它从一个文件调用模块,该文件是' HomescreenscrollCopy31' 。这完全没问题。

唯一的问题是模块中有一个线程似乎无法运行。

以下是登录屏幕中的代码:

def login():
    content = nameentry.get()
    content1 = IDentry.get()
    if content == "1" and content1 == "1":
        root.destroy()
        from HomescreenscrollCopy31 import FullScreenApp

HomescreenscrollCopy31.py文件如下所示,

class FullScreenApp(object):
     def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

    def trick(threadName, sleepTime):
        while 1 < 2:
            .....

    try:
        t = threading.Thread(target=trick, args=("Trick running", 5))
        t.daemon = True
        t.start()
    except: Exception,
    print "start up"

它似乎贯穿HomescreenscrollCopy31.py并且礼貌地打印了#34;启动&#34;只是为了取笑我,因为它从来没有真正运行过线程因此应该打印&#34; Trick running&#34;输出

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我认为用这种方式写它会更好。

def login():
    content = nameentry.get()
    content1 = IDentry.get()
    if content == "1" and content1 == "1":
        root.destroy()
        from HomescreenscrollCopy31 import FullScreenApp
        myFullScreenApp = FullScreenApp(...)  # you need to give it some input, like master, to initialize an instance for FullScreenApp class




class FullScreenApp(object):

    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)   

        # these code will be executed when instance initializing 
        t = threading.Thread(target=self.trick, args=["Trick running", 5])
        t.daemon = True
        t.start()


    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

    def trick(threadName, sleepTime):
        while 1 < 2:
            .....
  1. 您只需要初始化类的实例以获取线程 运行。如果使用staticmethod方式,它将使代码更多 很复杂,我不推荐。
  2. 调用新线程时,args应该是列表([])但不是a 元组(())。
  3. 您可以使用1而不是1&lt; 2。无论如何,这不是 主要问题。 :)
  4. 希望它有所帮助。