我的 Tkinter 代码:
from tkinter import Tk, Label, Entry, Button, END
from PIL import ImageTk, Image
class InputWindow():
def __init__(self, *args, **kwargs):
self.root = Tk()
self.root.title('Image Captcha')
self.root.configure(background='#ffe75c')
# Initializing the Variables to be defined later
image_label = Label(self.root)
# Defining the Input Box and placing it in the window
self.entry = Entry(self.root, width=10, borderwidth=5, font="Arial 15", justify="center")
self.entry.grid(row=2, column=0)
# Removing the contents of the input box.
self.entry.delete(0, END)
image_url = kwargs.get('captcha')
im = Image.open(requests.get(image_url, stream=True, timeout=5).raw)
image_display = ImageTk.PhotoImage(im, master=self.root)
# Removing the previous Image (if present) and
# displaying a new one.
image_label.grid_forget()
image_label = Label(self.root, image=image_display)
image_label.grid(row=1, column=0, columnspan=2, padx=10)
# Defining the submit button
submit_button = Button(self.root, text="Submit", font="Arial 10", command=lambda: self.get())
submit_button.grid(row=3, column=0, columnspan=2, pady=10)
self.root.mainloop()
def get(self):
if self.entry.get():
text = self.entry.get()
self.root.quit()
return text
self.root.quit()
return False
我在我的函数中这样称呼它:
solver = InputWindow(captcha = img_link)
captcha_str = solver.get()
solver.root.destroy()
所以这工作正常,因为当我运行时它会关闭:
if __name__ == '__main__':
但是,当我从另一个函数运行它时,窗口仍然存在并且不会关闭。我希望它在向我提供输入的文本后关闭。我用 destroy() 替换了 quit() 但没有成功。
如有任何帮助,我们将不胜感激。感谢您的关注和时间。
OZooHA
答案是在 captcha_str 之后添加一行来销毁窗口:
solver = InputWindow(captcha = img_link)
captcha_str = solver.get()
solver.root.destroy()