我在尝试从同一个函数内部追加到两个不同的列表时遇到了奇怪的行为。
x = 0
y = 0
list_1 = []
list_2 = []
def append_function(self):
self.x += 1
self.y += 1
self.list_1.append(self.x)
self.list_2.append(self.y)
print self.list_1
print self.list_2
我希望运行该函数一次的输出是:
[1]
[1]
如果我跑两次,我会期待:
[1,2]
[1,2]
我从运行该函数获得的实际输出是:
[1]
当我运行该功能两次时,我得到:
[1]
[1,2]
每次运行该功能时,第一个列表都会落后。这只发生在我在GUI类中运行代码时。否则它会按预期运行。有谁知道为什么会发生这种情况或知道解决方法?
以下是整个计划:
#imports
from PyQt4 import QtGui
from PyQt4 import QtCore
import ui_sof_test #Gui File
import sys
class Worker(QtCore.QThread):
def run(self):
pass
class Gui(QtGui.QMainWindow, ui_sof_test.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.start()
self.pushButton.clicked.connect(self.append_function)
x = 0
y = 0
list_1 = []
list_2 = []
def append_function(self):
self.x += 1
self.y += 1
self.list_1.append(self.x)
self.list_2.append(self.y)
print self.list_1
print self.list_2
#------------------------------------------------------------------------------------------------#
# Worker Thread(s) Setup #
##################################################################################################
def start(self):
self.setupWorker()
def setupWorker(self):
self.work = Worker()
#self.work.mcx.connect(self.setxy,QtCore.Qt.QueuedConnection)
#self.work.mcy.connect(self.move_cur_lifty,QtCore.Qt.QueuedConnection)
if not self.work.isRunning():#if the thread has not been started let's kick it off
self.work.start()
def main():
app = QtGui.QApplication(sys.argv) # A new instance of QApplication
form = Gui() # We set the form to be our ExampleApp (design)
form.show() # Show the form
app.exec_() # and execute the. app
if __name__ == '__main__': # if we're running file directly and not importing it
main() # run the main function
答案 0 :(得分:0)
这个问题是Spyder IDE中Iron Python控制台所独有的。在另一个python终端中运行代码会产生预期的结果。