简体   繁体   中英

How do I show, hide and show tkinter canvas after a period of time?

I'm trying to show and hide and show the canvas. The canvas does not even appear when I run the program and seems to get stuck in a loop.

import tkinter as tk
import time
    

class Test():
    def __init__(self):
       self.root = tk.Tk()
       self.canvas = tk.Canvas(self.root, bg="black", width=550, height=820)

    def main(self):
        time.sleep(2)
        self.canvas.pack()
        time.sleep(2)
        self.canvas.pack_forget()
        time.sleep(2)
        self.canvas.pack()
        self.root.mainloop()
        

a = Test()
a.main()

I see some problems here

  1. You should use mainloop method inside __init__ function
  2. You should update your elements ( .update() ) to make it work
  3. U simply cannot occour events like that
  4. Dont use sleep function Using .after method is slightly better in tkinter

I've modified your code to something like this:

import tkinter as tk

class Test():
    def __init__(self):
       self.root = tk.Tk()
       self.canvas = tk.Canvas(self.root, bg='black', width=550, height=820)
       self.btn = tk.Button(self.root,text='main func',command=self.main)
       self.btn.pack()
       self.root.mainloop()

    def main(self):
        self.root.after(2000)
        self.canvas.pack()
        self.canvas.update()
        self.root.after(2000)
        self.canvas.pack_forget()
        self.canvas.update()
        self.root.after(2000)
        self.canvas.pack()
        self.canvas.update()        

a = Test()

As u can see I've added a button to occur the event for me. Try to find the moment in your program where the event can be occured. For example: I click the button to generate some strings. Its also runs main funcion.

I hope i helped you enough

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