我想提示用户在函数的中间选择yes和no,然后继续相应的函数。怎么可能?在
这是我的代码:
def download_popup(file_name, url, size, threshold):
root = Tk()
label = Label(root,
text="The file {file} at {url} is {size}Bytes large which is larger than your threshold({threshold})."
"\nShall I still download it?".format(file_name, url, size, threshold))
yes = ttk.Button(root, width=5, text="yse",
command=lambda: return True)
no = ttk.Button(root, width=5, text="no",
command=lambda: return False)
label.grid(column=0, row=0, colspan=2)
yes.grid(column=0, row=1)
no.grid(column=1, row=1)
mainloop()
# somewhere else in the middle of a function I have:
if response.getheader('Content-Length') > setting.download_threshold_var.get():
# I want the function to wait in this line:
if download_popup(file, url, response.getheader('Content-Length'), setting.download_threshold_var.get()):
out_file.write(response.read())
当然,我的代码是无稽之谈,我只是为了更好地展示我真正想要的。在
顺便说一下,我可以将函数拆分为3个函数,第一个函数调用download_popup(),download_popup根据用户的选择调用第二个或第三个函数,但我需要一个更优雅的解决方案。在
最简单的解决方案是使用预定义的对话框之一,例如
askyesno
。如果您想要自己的对话,模式是创建一个Toplevel
的实例,然后调用wait_window
,直到窗口被破坏后才会返回。在使用预定义的对话框
在Python3中,内置对话框位于子模块
messagebox
。要询问是/否问题,可以使用askyesno
。例如:创建自己的对话框
关键是创建一个顶层,然后等待它被销毁。要从对话框中获取值,可以使用全局变量或实例变量。在
通常最好使用类而不是全局变量,但简单起见,我将给出一个使用全局变量的答案:
^{pr2}$您可以使用
Button
小部件的command
属性来调用def
。在这意味着你不必为了得到用户的答案而把所有事情都搁置起来。您只需设置两个
def
(或者其中一个并在开始时传入一个不同的参数)并在按下按钮时调用它们。在见下文:
如果您需要使用一个函数来完成此操作,您可以使用以下类似的方法:
^{pr2}$相关问题 更多 >
编程相关推荐