0

我有这个脚本,我想使用 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)
4

1 回答 1

0

用于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)

在此处输入图像描述

于 2017-12-13T00:53:06.727 回答