【问题标题】:How can I access the TextButton custom data property by clicking on the button in Python's Flet module?如何通过单击 Python 的 Flet 模块中的按钮来访问 TextButton 自定义数据属性?
【发布时间】:2023-01-16 07:36:31
【问题描述】:

我正在使用 Flet 模块创建一个简单的 GUI。

我想访问按钮上的自定义数据。但是,使用 clicked 方法,按钮的事件处理程序似乎使用它的数据属性,返回空字符串。因此,该方法不打印任何内容。

使用机群 0.1.62, Python 3.10

import flet
from flet import UserControl, TextButton, Row, Page


class Test(UserControl):
    def __init__(self):
        super().__init__()

        self.text_button = TextButton(text='test', data='test', on_click=self.clicked)
        self.view = Row(controls=[self.text_button])

    def clicked(self, e):
        print(e.data, ' was clicked')

    def build(self):
        return self.view


def main(page: Page):
    t = Test()
    page.add(t)


app = flet.app(target=main)

在 Calculor 示例的 flet 教程中,您可以使用相同的方法为 on_click 参数设置多个按钮。

这是示例代码的一部分,它指的是处理事件: https://flet.dev/docs/tutorials/python-calculator/

现在让我们让计算器完成它的工作。我们将为所有按钮使用相同的事件处理程序,并使用数据属性根据单击的按钮区分操作。对于每个 ElevatedButton 控件,指定 on_click=self.button_clicked 事件并将数据属性设置为按钮的文本,例如:

ft.ElevatedButton(
    text="AC",
    bgcolor=ft.colors.BLUE_GREY_100,
    color=ft.colors.BLACK,
    expand=1,
    on_click=self.button_clicked,
    data="AC",
)

下面是on_click 事件处理程序,它将在单击"AC"按钮时重置文本值:

def button_clicked(self, e):
    if e.data == "AC":
        self.result.value = "0"

使用类似的方法,为每个按钮指定 on_click 事件和数据属性,并根据 e.data 值将预期操作添加到 button_clicked 事件处理程序。

我正在寻找一种使用 TextButton 获得相同结果的方法, 感谢您的帮助!

【问题讨论】:

    标签: python-3.x flet


    【解决方案1】:

    我找到了我自己问题的答案。显然,在我使用的 flet 版本中,必须通过 control 实例属性查找数据属性。 所以 我在我的问题的代码中试过这个:

    def clicked(self, e):
            print(e.control.data, ' was clicked')
    

    代替:

    def clicked(self, e):
            print(e.data, ' was clicked')
    

    出于好奇,我尝试了一下,它奏效了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多