【发布时间】:2015-12-09 15:11:55
【问题描述】:
我会尽力以清晰的方式解释这个问题,它是我为 A 级项目开发的一个更大的软件的一部分,该项目旨在创建一个简单版本的一个图形编程系统(想想猴子用大约 7 个命令制作的从头开始)。
我目前的麻烦源于需要在一个独特的线程上运行一个执行函数,该线程能够与用户界面交互,该界面显示执行用户制作的代码块(使用 Tkinter 库编写)的结果主线程。该函数旨在遍历一个动态列表,该列表包含有关用户“代码”的信息,可以循环遍历并“逐行”处理。
执行开始时会出现此问题,并且线程函数尝试调用属于用户界面类的函数。我对多线程的了解有限,所以我很可能违反了一些重要规则并以没有意义的方式做事,在这里提供帮助会很棒。
我已经实现了接近我之前所追求的功能,但总是以不同的方式出现一些错误(主要是由于我最初尝试在第二个线程中打开一个 tkinter 窗口......一个坏主意)。
据我所知,我当前的代码在打开第二个线程、在主线程中打开 UI 并开始在第二个线程中运行执行功能方面起作用。为了解释这个问题,我创建了一小段代码,它在相同的基础上工作,并产生相同的“无类型”错误,我会使用原始代码,但它很笨重,而且更烦人比下面:
from tkinter import *
import threading
#Represents what would be my main code
class MainClass():
#attributes for instances of each of the other classes
outputUI = None
threadingObject = None
#attempt to open second thread and the output ui
def beginExecute(self):
self.threadingObject = ThreadingClass()
self.outputUI = OutputUI()
#called by function of the threaded class, attempts to refer to instance
#of "outputUI" created in the "begin execute" function
def execute(self):
return self.outputUI.functionThatReturns()
#class for the output ui - just a blank box
class OutputUI():
#constructor to make a window
def __init__(self):
root = Tk()
root.title = ("Window in main thread")
root.mainloop()
#function to return a string when called
def functionThatReturns(self):
return("I'm a real object, look I exist! Maybe")
#inherits from threading library, contains threading... (this is where my
#understanding gets more patchy)
class ThreadingClass(threading.Thread):
#constructor - create new thread, run the thread...
def __init__(self):
threading.Thread.__init__(self)
self.start()
#auto called by self.start() ^ (as far as I'm aware)
def run(self):
#attempt to run the main classes "execute" function
print(mainClass.execute())
#create instance of the main class, then attempt execution of some
#threading
mainClass = MainClass()
mainClass.beginExecute()
运行此代码时,会产生以下结果:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python34\lib\threading.py", line 920, in _bootstrap_inner
self.run()
File "H:/Programs/Python/more more threading tests.py", line 33, in run
print(mainClass.execute())
File "H:/Programs/Python/more more threading tests.py", line 14, in execute
return self.outputUI.functionThatReturns()
AttributeError: 'NoneType' object has no attribute 'functionThatReturns'
我想应该注意的是,tkinter 窗口按我希望的方式打开,并且线程类做了它应该做的事情,但似乎没有意识到输出 UI 的存在。我认为这是由于我对面向对象和线程的某些部分知之甚少。
那么,有没有一种方法可以从线程函数调用输出 ui 中的函数?还是有类似的解决方法? 需要注意的是,我没有将输出窗口的创建放在主类的 init 函数中,因为我需要能够创建输出窗口并因此启动线程等另一个输入。
很抱歉,如果这没有意义,请对我大喊大叫,我会尝试解决它,但非常感谢您的帮助,干杯。
【问题讨论】:
标签: python multithreading object attributeerror nonetype