Frame won't get destroyed before function executes
Question:
I am trying to get a Tkinter canvas. (save it as an image using the PIL library)
I have a button inside a frame that runs the function below.
I want to destroy the frame right before it saves the canvas but I can’t figure out how to do it.
here is what I’ve tried so far:
from tkinter import *
from PIL import ImageGrab
root = Tk()
canvas = Canvas(root,width=root.winfo_screenwidth(),height=root.winfo_screenheight(), bg="white",highlightthickness=0,cursor='dot')
canvas.pack(side=RIGHT,fill=Y)
save_canvas_frame = Frame(root,width=84,height=root.winfo_screenheight(),bg="#EFEFEF")
save_canvas_frame.place(x=0,y=0)
def save():
# Close the frame <---
save_canvas_frame.destroy()
# Run the rest of the function <---
x=root.winfo_rootx()+canvas.winfo_x()
y=root.winfo_rooty()+canvas.winfo_y()
x1=x+canvas.winfo_width()
y1=y+canvas.winfo_height()
pic = ImageGrab.grab((x, y, x1, y1))
pic.save("pic.png")
save_button = Button(save_canvas_frame,text="Save Canvas",command=save)
save_button.place(x=0,y=0)
root.mainloop()
Answers:
One possible solution is to create 2 functions and call one by .after()
:
def save_img():
x=canvas.winfo_x()
y=canvas.winfo_y()
x1=x+canvas.winfo_width()
y1=y+canvas.winfo_height()
print(x,y,x1,y1)
pic= ImageGrab.grab((x, y, x1, y1))
pic.save("pic.png")
def save():
# Close the frame
save_canvas_frame.destroy()
root.after(1,save_img)
I am trying to get a Tkinter canvas. (save it as an image using the PIL library)
I have a button inside a frame that runs the function below.
I want to destroy the frame right before it saves the canvas but I can’t figure out how to do it.
here is what I’ve tried so far:
from tkinter import *
from PIL import ImageGrab
root = Tk()
canvas = Canvas(root,width=root.winfo_screenwidth(),height=root.winfo_screenheight(), bg="white",highlightthickness=0,cursor='dot')
canvas.pack(side=RIGHT,fill=Y)
save_canvas_frame = Frame(root,width=84,height=root.winfo_screenheight(),bg="#EFEFEF")
save_canvas_frame.place(x=0,y=0)
def save():
# Close the frame <---
save_canvas_frame.destroy()
# Run the rest of the function <---
x=root.winfo_rootx()+canvas.winfo_x()
y=root.winfo_rooty()+canvas.winfo_y()
x1=x+canvas.winfo_width()
y1=y+canvas.winfo_height()
pic = ImageGrab.grab((x, y, x1, y1))
pic.save("pic.png")
save_button = Button(save_canvas_frame,text="Save Canvas",command=save)
save_button.place(x=0,y=0)
root.mainloop()
One possible solution is to create 2 functions and call one by .after()
:
def save_img():
x=canvas.winfo_x()
y=canvas.winfo_y()
x1=x+canvas.winfo_width()
y1=y+canvas.winfo_height()
print(x,y,x1,y1)
pic= ImageGrab.grab((x, y, x1, y1))
pic.save("pic.png")
def save():
# Close the frame
save_canvas_frame.destroy()
root.after(1,save_img)