简体   繁体   中英

How to enable an element again after a process has been completed in Tkinter

So I have a notebook with 2 pages. Initially tab1 is disable. Clicking a button in tab0 triggers an external process of creating a file. Only once this file is created should tab1 be enabled again.I can't edit the code that creates this file and creating it take some time so in the meantime my code should constantly check if it is created and then enable the tab... How can I do this is tkinter?

from tkinter import *
from tkinter import ttk


root = Tk()
note = ttk.Notebook(root)

tab0 = ttk.Frame(note)
tab1 = ttk.Frame(note)

note.add(tab0)
note.add(tab1, state="disabled") # tab disabled
note.pack(expand = 1, fill = "both")

# <----------------tab0------------------>
canvas_home = Canvas(tab0,bg='#398FFF')
canvas_home.pack(expand=True,fill=BOTH)

# In my case create_file is being imported...
def create_file():
    import time
    time.sleep(100) # assume a file is being created
button = Button(canvas_home, text="Create file",command=create_file)
button.grid()
# <----------------tab1------------------>
import os
if os.path.exists('filename'):
    note.tab(0, state="normal") # tab enabled

if __name__ == "__main__":
    root.mainloop()

Some mistakes:You didn't put your button in your Frame.You want to enable tab1 but you enable tab0

Assume you want to create a txt file called create_text ,You could use .after() to check the file whether exist.

In this example,it will check the file per 0.1 second:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os


def create_file():
    create_path = filedialog.asksaveasfilename()
    if create_path:
        with open(create_path, "w") as f: # create a empty text
            pass

def check_file():
    if os.path.exists('create_text.txt'): # check whether it exists
        note.tab(1, state="normal")
    else:
        root.after(100, check_file)


root = Tk()
note = ttk.Notebook(root)

tab0 = ttk.Frame(note)
tab1 = ttk.Frame(note)

note.add(tab0)
note.add(tab1, state="disabled")  # tab disabled
note.pack(expand=1, fill="both")

# <----------------tab0------------------>
canvas_home = Canvas(tab0, bg='#398FFF')
canvas_home.pack(expand=True, fill=BOTH)

button = Button(canvas_home, text="Create file", command=create_file)
button.grid()

root.after(100, check_file)

if __name__ == "__main__":
    root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM