【发布时间】:2020-05-25 17:08:04
【问题描述】:
我有一个 python 脚本,它使用 Tkinter 创建一个 GUI 窗口。创建窗口并读取输入后,我希望执行继续进行到 while 循环,但由于窗口没有被破坏,因此执行永远不会恢复。我希望它在读取输入后恢复。但是在这里显示“你输入了 xxxx”之后,屏幕冻结并且执行永远不会回到之前的 while 循环。我该如何解决?我不想每次都创建窗口
from PIL import ImageGrab, Image
from glob import glob
from io import BytesIO
import time
import tkinter as tk
window = None
entry = None
window_created = False
x = None
name_of_file = None
input_wait = False
def handle_click(event):
global name_of_file
name_of_file = entry.get()
print("You Entered " + name_of_file)
entry.delete(0, tk.END)
hide_window(window)
def show_window(window):
window.update()
window.deiconify()
def hide_window(window):
window.update()
window.withdraw()
def create_window():
global window
global entry
window = tk.Tk()
window.geometry("600x600")
window.title("Name for your image")
label = tk.Label(text="What do you want to name the image?")
entry = tk.Entry()
button = tk.Button(text="Create")
button.bind("<Button-1>", handle_click)
window.bind("<Return>", handle_click)
label.pack()
entry.pack()
button.pack()
window.mainloop()
while True:
print("Looping")
image_list = map(Image.open, glob('*.png'))
presentItem = ImageGrab.grabclipboard()
if presentItem is not None:
with BytesIO() as f:
presentItem.save(f, format='PNG')
x = Image.open(f)
if x not in image_list:
print("New item found")
if not window_created:
create_window()
window_created = True
print("Resumes")
else:
show_window(window)
print("Resumes")
presentItem.save(name_of_file + '.png', 'PNG')
else:
print("No item in clipboard")
time.sleep(0.1)
【问题讨论】:
-
将您的
while ...替换为.after(...。阅读tkinter: how to use after method -
事情不会真正起作用,因为在这里我只想在输入输入后恢复执行
-
不想每次都创建窗口怎么办?我只想创建一次
-
两种方式:1.使用 OOP 来做到这一点,重建你的代码。这将只创建一次(参考如何使用 after 方法)2。还是使用
while循环,但是每次都需要创建。 -
事情不会真正起作用...恢复...仅...输入输入:您可以中断/恢复after_loop_function 随心所欲。 BREAK:不要再拨打
.after(...。 RESUME:再次调用after_loop_function。
标签: python python-3.x python-2.7 tkinter