在tkinter中禁用撤消按钮(python3.7)

问题描述 投票:-2回答:1

我想创建一个撤销按钮,当它无法撤销时,将其状态更改为禁用。我只想知道是否有一个函数知道文件是否可撤消。

python-3.x tkinter undo
1个回答
-1
投票

这是一个非常基本的原型,应该演示一个撤消按钮:

import tkinter as tk

undo_history = []
n = 0

def undo_action():
    x = undo_history.pop()
    if len(undo_history) == 0:
        undoBtn.config(state=tk.DISABLED)

    print("Un-did this:", x)

def do_action():
    global n
    n += 1
    undo_history.append(f"Action {n}")
    if len(undo_history) == 1:
        undoBtn.config(state=tk.NORMAL)

    print("Did this:", undo_history[-1])


root = tk.Tk()

undoBtn   = tk.Button(root, text="Undo", command=undo_action)
actionBtn = tk.Button(root, text="Do something!", command=do_action)

undoBtn.pack()
actionBtn.pack()

root.mainloop()

关于将其应用于文件,您可以读取文件,并每隔几秒钟记录一次其内容。如果它们已更改,则在do_action中将其记录为新状态。然后,您可以在undo_action中将更改写入文件。

下面是一个例子:

import tkinter as tk, time, threading

filename = "test.txt"

undo_history = []

with open(filename) as f:
    prev_state = f.read()
orig_state = prev_state

undo = False
def undo_action():
    global undo, prev_state
    undo = True

    x = undo_history.pop()
    if len(undo_history) == 0:
        undoBtn.config(state=tk.DISABLED) # disable btn

    if len(undo_history) > 0:
        state = undo_history[-1]
    else:
        state = orig_state

    prev_state = state
    open(filename, 'w').write(state)

    print("Un-did this:", x)
    print("New State:", state)

    undo = False

def check_action():
    global prev_state

    while undo: # undo_action is running
        continue

    with open(filename) as f:
        state = f.read()

    if state == prev_state:
        return

    prev_state = state

    undo_history.append(state)
    undoBtn.config(state=tk.NORMAL)

    print("State:", state)

def run_checks():
    while True: # check for changes every 0.5 secs
        check_action()
        time.sleep(0.5)

root = tk.Tk()

undoBtn = tk.Button(root, text="Undo", command=undo_action)
undoBtn.config(state=tk.DISABLED)
undoBtn.pack()

t = threading.Thread(target=run_checks)
t.start()

root.mainloop()

此代码每0.5秒对文件内容进行一次自动检查,并允许您撤消那些更改。希望这对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.