用于deiconify()
显示Tk()
后窗并使用它代替Toplevel()
顺便说一句:回调不必返回值,因为没有人接收这个值。
import tkinter.filedialog
from PIL import Image, ImageTk
# --- functions ---
def callback(event):
global ps # at the beginning to make it more readable
print("Starting pixel of object is: ", event.x, event.y)
ps[0] = event.x
ps[1] = event.y
# --- main ---
ps = [0, 0]
root = tkinter.Tk()
root.withdraw()
image = tkinter.filedialog.askopenfilename()
img = Image.open(image)
image_tk = ImageTk.PhotoImage(img)
root.deiconify() # <-- show `root` again
canvas = tkinter.Canvas(root, width=img.size[0], height=img.size[1])
canvas.pack()
canvas.create_image(img.size[0] // 2, img.size[1] // 2, image=image_tk)
canvas.bind("<Button-1>", callback)
tkinter.mainloop()
print(ps)
顺便说一句:您可以使用 Label 来显示它
import tkinter
import tkinter.filedialog
from PIL import Image, ImageTk
def callback(event):
global ps
print("Starting pixel of object is: ", event.x, event.y)
ps[0] = event.x
ps[1] = event.y
label['text'] = str(ps)
# --- main ---
ps = [0, 0]
root = tkinter.Tk()
root.withdraw()
image = tkinter.filedialog.askopenfilename()
img = Image.open(image)
image_tk = ImageTk.PhotoImage(img)
root.deiconify()
canvas = tkinter.Canvas(root, width=img.size[0], height=img.size[1])
canvas.pack()
canvas.create_image(img.size[0] // 2, img.size[1] // 2, image=image_tk)
canvas.bind("<Button-1>", callback)
label = tkinter.Label(root)
label.pack()
tkinter.mainloop()
print(ps)