如何在Tkinter中触发comand中按钮的更改?

2024-06-28 19:02:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新手。我需要更改button及其state的文本,然后执行一些操作,最后再次更改其文本和状态

问题是,更改只在函数结束后应用,跳过状态和文本的第一次更改。它从不将Buttons文本更改为“加载”,并且从不禁用该按钮

以下是我遇到的问题的代码:

#!/usr/bin/env python
import tkinter as tk
import time


class Application(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack(fill=tk.BOTH, expand=1)
        self.create_widgets()

    def create_widgets(self):
        self.master.title("CW POS")

        cierre = tk.Button(
            self.master,
            command=self.re_imprimir_ultimo_cierre)

        cierre["text"] = "foo"
        cierre.pack(fill=tk.BOTH, expand=1)
        self._cierre = cierre

        salir = tk.Button(self.master, text="quit", command=self.salir)
        salir.pack(fill=tk.BOTH, expand=1)


    def salir(self):
        exit()

    def re_imprimir_ultimo_cierre(self):
        self._cierre["text"] = "Loading..."
        self._cierre["state"] = tk.DISABLED

        # TODO: magic
        time.sleep(2)

        self._cierre["text"] = "foo"
        self._cierre["state"] = tk.NORMAL



root = tk.Tk()
root.geometry("240x180")
root.resizable(False, False)
app = Application(root)
root.mainloop()

当按钮进行计算时,如何使按钮显示text="loading"state=DISABLED


Tags: text文本selfmasterdefrootfill按钮
1条回答
网友
1楼 · 发布于 2024-06-28 19:02:45

这个问题有一个很快的解决方法,你只需要更新按钮,一旦你把它的文本改为“加载”(self._cierre["text"] = "Loading..."

    def re_imprimir_ultimo_cierre(self):
        self._cierre["text"] = "Loading..."
        self._cierre["state"] = tk.DISABLED

        self._cierre.update() # This is the line I added

        # TODO: magic
        time.sleep(2)

        self._cierre["text"] = "foo"
        self._cierre["state"] = tk.NORMAL

这只是在您更改文本和状态后更新按钮状态

From what I understand this is because a button will run all the code within its command, before updating anything on the screen, so you essentially have to force the button to update itself within its command.

希望这有帮助:)

相关问题 更多 >