You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Guizero PushButton的command参数未按按钮却执行函数问题

问题:ButtonGroup选择菜单中函数提前执行的问题

使用guizero的ButtonGroup构建选择菜单,希望用户选择功能后点击PushButton确认执行,但程序运行时Funzione1会立即执行,无需等待用户选择和点击按钮。若不给PushButton设置command参数,按钮点击无反应。

原因分析

问题出在PushButton的command参数设置上:

button = PushButton(app, command=(semen(int(choice.value))), text="Seleziona")

这里直接执行了semen(int(choice.value)),并把函数执行的结果(而非函数本身)传给了command参数,导致程序启动时就调用了semen,进而触发Funzione1。command参数需要接收的是可调用的函数对象,而不是函数执行后的返回值。

解决方法

用lambda表达式包装函数调用,这样只有当按钮被点击时,才会执行semen函数并传入当前选择的choice.value:

修正后的完整代码

from guizero import App, Text, ButtonGroup, PushButton

def MainMenu():
    app = App(title="Titolo")

    def semen(menu):
        if 0 <= menu <= 2:
            if menu == 1:
                Funzione1()
            elif menu == 2:
                Funzione2()
            elif menu == 0:
                # Uscita
                print(0)
                return False

    text_1 = Text(app, text=" ")
    text_2 = Text(app, text="Cosa vuoi fare?")
    text_1 = Text(app, text=" ")
    choice = ButtonGroup(app, options=[
        ["Funzione1", 1],
        ["Funzione2", 2],
        ["Chiudere e uscire", 0]])
    text_1 = Text(app, text=" ")
    # 使用lambda延迟函数执行,点击按钮时才调用semen
    button = PushButton(app, command=lambda: semen(int(choice.value)), text="Seleziona")
    app.display()

def Funzione1():
    print('Eseguo funzione1')

def Funzione2():
    print('Eseguo funzione2')

MainMenu()

补充说明

也可以修改semen函数,让它内部直接获取choice.value,这样command参数直接传入semen即可:

def semen():
    menu = int(choice.value)
    if 0 <= menu <= 2:
        if menu == 1:
            Funzione1()
        elif menu == 2:
            Funzione2()
        elif menu == 0:
            print(0)
            return False

# 按钮设置改为
button = PushButton(app, command=semen, text="Seleziona")

这种方式代码更简洁,适合不需要额外传参的场景。

内容的提问来源于stack exchange,提问作者MoDieSse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:35:07