怎么在函数中等待用户触发的Python代码?

2024-04-19 21:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提示用户在函数的中间选择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根据用户的选择调用第二个或第三个函数,但我需要一个更优雅的解决方案。在


Tags: 函数notexturlsizethresholdresponsedownload
2条回答

最简单的解决方案是使用预定义的对话框之一,例如askyesno。如果您想要自己的对话,模式是创建一个Toplevel的实例,然后调用wait_window,直到窗口被破坏后才会返回。在

使用预定义的对话框

在Python3中,内置对话框位于子模块messagebox。要询问是/否问题,可以使用askyesno。例如:

import tkinter as tk
from tkinter import messagebox

def download_popup(file_name, url, size, threshold):
    ...
    answer = tk.messagebox.askyesno("Confirmation", "The file...")
    if answer:
        print("you answered yes")
    else:
        print("you answered no")

创建自己的对话框

关键是创建一个顶层,然后等待它被销毁。要从对话框中获取值,可以使用全局变量或实例变量。在

通常最好使用类而不是全局变量,但简单起见,我将给出一个使用全局变量的答案:

^{pr2}$

您可以使用Button小部件的command属性来调用def。在

这意味着你不必为了得到用户的答案而把所有事情都搁置起来。您只需设置两个def(或者其中一个并在开始时传入一个不同的参数)并在按下按钮时调用它们。在

见下文:

from tkinter import *

root = Tk()

def yes():
    print("The user pressed yes, now do something you fool!")

def no():
    print("Oh no, they pressed no. Quick, panic!")

yes = Button(root, text="Yes", command=yes)

no = Button(root, text="No", command=no)

yes.pack()
no.pack()

root.mainloop()

如果您需要使用一个函数来完成此操作,您可以使用以下类似的方法:

^{pr2}$

相关问题 更多 >