使用Exec在Python中设置按钮图像 - 有更好的方法吗?

发布于 2025-01-28 21:08:53 字数 774 浏览 1 评论 0原文

我正在为TKINTER编写Python代码,以为四个不同按钮设置各种图像。我将四个整数为0-3的方法发送到该方法,并根据此列表将四个按钮的图像设置为图像btn_img_a0,a1,a2,a2,a3(等)。 如果/elif语句涵盖所有可能性,我可以写16张,但是我这样做了:

def set_btn_status():  #changes the buttons to reflect button_status
    global button_status
    image_for_A = 'btn_img_A' + str(button_status[0])
    exec ('button_A.configure(image = '+image_for_A+')')
    image_for_B = 'btn_img_B' + str(button_status[1])
    exec ('button_B.configure(image = '+image_for_B+')')
    image_for_C = 'btn_img_C' + str(button_status[2])
    exec ('button_C.configure(image = '+image_for_C+')')
    image_for_D = 'btn_img_D' + str(button_status[3])
    exec ('button_D.configure(image = '+image_for_D+')')

我告诉我使用Exec是有风险的,但是这将代码削减到8行而不是16行,而且工作正常 - 这是合理的,还是在那里更好的方法?

I'm writing a Python code for tkinter to set various images for four different buttons. I send to the method a list of four integers, 0-3, and it sets the image of the four buttons to image btn_img_A0, A1, A2, A3 (etc for the others) based on this list.
I could write 16 if/elif statements to cover all possibilities, but I did this:

def set_btn_status():  #changes the buttons to reflect button_status
    global button_status
    image_for_A = 'btn_img_A' + str(button_status[0])
    exec ('button_A.configure(image = '+image_for_A+')')
    image_for_B = 'btn_img_B' + str(button_status[1])
    exec ('button_B.configure(image = '+image_for_B+')')
    image_for_C = 'btn_img_C' + str(button_status[2])
    exec ('button_C.configure(image = '+image_for_C+')')
    image_for_D = 'btn_img_D' + str(button_status[3])
    exec ('button_D.configure(image = '+image_for_D+')')

I'm told that using exec is risky, but this cuts the code to 8 lines instead of 16 and works fine - is this reasonable, or is there a better way??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文