Python 如何使用函数返回值作为条件?

Python 如何使用函数返回值作为条件?,python,function,python-3.x,return,Python,Function,Python 3.x,Return,我正在尝试为我正在处理的东西制作一个开始游戏按钮,但我不知道如何使用函数的返回值。这是我的例子 start_game = ttk.Button(frame, text="Start Game", command=startgame) start_game.grid(column=1, row=2) def startgame(): return True if startgame() is True: """Run the game""" 我知道这是错误的,我花了一些时间寻

我正在尝试为我正在处理的东西制作一个开始游戏按钮,但我不知道如何使用函数的返回值。这是我的例子

start_game = ttk.Button(frame, text="Start Game", command=startgame)
start_game.grid(column=1, row=2)

def startgame():
    return True

if startgame() is True:
    """Run the game"""

我知道这是错误的,我花了一些时间寻找解释,但我似乎找到的只是如何打印函数的返回值。

您的代码需要是这样的,您不需要“是真的”

但StartName似乎已经是真的了,所以您可以编写代码或将其定义为函数,如

def game():
   """Game Code"""
然后您可以使用

game() 
由于运行函数,只需将游戏代码放入该函数:

start_game = ttk.Button(frame, text="Start Game", command=rungame)
start_game.grid(column=1, row=2)

def rungame():
    """Run the game"""

在原始代码中,代码
startgame()
执行函数
startgame
,该函数返回
True
,而不考虑任何其他代码

您可能一直追求的模式需要协作的共同例程、事件循环、多线程或其他形式的并发,这对于现在的主题来说太复杂了,但简化的伪代码算法如下所示:

start_game = ttk.Button(frame, text="Start Game", command=allow_game)
start_game.grid(column=1, row=2)

game_allowed = False
def allow_game()
    global game_allowed
    game_allowed = True


while True:
    if game_allowed:
        """Run the game"""
        break
    else:
        """run an infinite loop waiting for game_allowed to be True,
           but you must run it in a way that allows ttk to execute the 
           allow_game(), not this simple while loop
        """

你为什么认为那是错误的<代码>如果startName():可以正常工作。如果您试图从
命令启动
,只需将游戏代码包装成一个函数,而不是
If
块。因为当我运行它时,它只是假设start\u game()为真,然后我甚至按下按钮,整个游戏就开始了。我想把它放到一个函数中,但我真的只是想了解如何从函数中返回一些东西,然后将其作为一个条件,因为我仍然不太了解它是如何工作的。我的建议是:暂时远离GUI应用程序。首先理解核心语言。@Doc_当然是,这就是
startgame
返回的结果。我支持上面的评论,好吧,我想我明白了。这没什么不同<代码>真是真
,这不是问题所在。如果你突出显示了更改和/或解释了更改(没有)的作用,这也会很有帮助。我试过了,但在我按下按钮之前游戏才刚刚开始…@Doc_Apes我以为你在条件方面遇到了问题。谢谢你的帮助,我意识到我的做法完全错了,但干杯!谢谢你的建议,我想这就是我要做的,我要做的,只是继续做一些我自己的研究,试着更好地理解函数。我添加了一些伪代码来解释你可能试图实现的模式,但它需要更加复杂才能真正工作
start_game = ttk.Button(frame, text="Start Game", command=allow_game)
start_game.grid(column=1, row=2)

game_allowed = False
def allow_game()
    global game_allowed
    game_allowed = True


while True:
    if game_allowed:
        """Run the game"""
        break
    else:
        """run an infinite loop waiting for game_allowed to be True,
           but you must run it in a way that allows ttk to execute the 
           allow_game(), not this simple while loop
        """