Tkinter顶层循环

时间:2017-12-13 00:27:18

标签: python image tkinter python-3.5 toplevel

我有这个脚本,我想使用Tkinter从目录中选择图像然后选择像素,但看起来像tkinter.mainloop()永远不会结束。请帮忙

import tkinter.filedialog
from PIL import Image, ImageTk


def callback(event):
    print("Starting pixel of object is: ", event.x, event.y)
    global ps
    ps[0] = event.x
    ps[1] = event.y
    return event.x, event.y


tkinter.Tk().withdraw()
image = tkinter.filedialog.askopenfilename()
ps = [0, 0]
window = tkinter.Toplevel()
img = Image.open(image)
canvas = tkinter.Canvas(window, width=img.size[0], height=img.size[1])
canvas.pack()
image_tk = ImageTk.PhotoImage(img)
canvas.create_image(img.size[0] // 2, img.size[1] // 2, image=image_tk)
canvas.bind("<Button-1>", callback)
tkinter.mainloop()
print(ps)

1 个答案:

答案 0 :(得分:0)

使用deiconify()显示Tk()窗口并使用它代替Toplevel()

BTW:回调不必返回值,因为没有人接收此值。

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)

BTW:您可以使用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)

enter image description here