-1
我使用_thread
模塊(因爲它更適合我的程序),我想將函數傳遞給我傳入線程的函數。但是,有可能僅將元組轉換爲_thread.start_new_thread()
函數,但函數不可迭代!Python 3:將函數傳遞給* args
@Willem Van Onsem - 這裏是完整的代碼。使用Pygame。
class PGMaster:
"""
Properties:
mainloopOn - exits program if False
Functions:
PGMaster.mainlooprunner()
Repeatedly runs Main function (must be overrided).
PgMaster.mainloop(subthread=False)
Wrapper for mainlooprunner. Subthread - will it run under MainThread? No if True.
"""
def winmode(self, dimensions, flags=0, caption='', depth=None):
"""
Flags are:
pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
pygame.OPENGL create an OpenGL-renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls
"""
if depth != None:
screenx = self.screen = pygame.display.set_mode(dimensions, flags, depth)
elif depth == None:
screenx = self.screen = pygame.display.set_mode(dimensions, flags)
pygame.display.set_caption(caption)
return screenx
def __init__(self, dimensions, flags=0, caption='', depth=None):
self.winmode(dimensions, flags, caption, depth)
self.mainloopOn = True
def mainlooprunner(self, function):
func = function
while self.mainloopOn:
func()
def mainlooprunnerx(self, *function):
func = function[0]
while self.mainloopOn:
func()
def mainloop(self, func, subthread=False):
if subthread:
functuple = tuple(func)
_thread.start_new_thread(self.mainlooprunnerx, functuple)
elif not subthread:
self.mainlooprunner(func)
. . .
if __name__ == '__main__':
root = PGMaster([1600, 900], pygame.DOUBLEBUF | pygame.RESIZABLE)
# vvv Real codes vvv
print(pygame.FULLSCREEN)
print(pygame.DOUBLEBUF)
print(pygame.HWSURFACE)
print(pygame.OPENGL)
print(pygame.RESIZABLE)
print(pygame.NOFRAME)
# ^^^ Real codes ^^^
def myloop():
print('Hello World!')
return
root.mainloop(myloop, True)
輸出:
Traceback (most recent call last): File "C:\Users\User\Desktop\PyGameUI\__init__.py", line 127, in <module> root.mainloop(myloop, True) File "C:\Users\User\Desktop\PyGameUI\__init__.py", line 100, in mainloop functuple = tuple(func) TypeError: 'function' object is not iterable
這不是真的我清楚你想達到什麼樣的,等你能給帶有輸入和一個錯誤消息/預期輸出的例子嗎? –
請勿使用以下劃線開頭的任何內容。這是python標記爲「受保護」的方式,開發人員不保證其行爲不會改變。 – gonczor
@gonczor它已被棄用,但我仍然使用它,因爲我不想定義嵌套類 - 它會降低代碼的可讀性。從文檔:「線程模塊由於其棄用而在_thread中重命名」。 –