Overview
不,你不必“画一个矩形,然后做一个循环”。你什么will所要做的就是导入某种 GUI 工具包,并使用该工具包内置的方法和对象。一般来说,其中一种方法是运行一个循环来侦听事件并根据这些事件调用函数。这个循环称为事件循环。因此,虽然这样的循环必须运行,但您不必创建循环。
Caveats
如果您希望通过提示(例如您链接到的视频中的提示)打开窗口,那么问题会有点棘手。这些工具包并不是为以这种方式使用而设计的。通常,您编写一个完整的基于 GUI 的程序,其中所有输入和输出都是通过小部件完成的。这并非不可能,但在我看来,学习时应该坚持所有文本或所有 GUI,而不是混合两者。
使用 Tkinter 的示例
例如,tkinter 就是这样的工具包之一。 Tkinter 是 python 内置的工具包。任何其他工具包(例如 wxPython、PyQT 等)都非常相似并且工作得一样好。 Tkinter 的优点是您可能已经拥有它,并且它是学习 GUI 编程的绝佳工具包。对于更高级的编程来说,它也很棒,尽管您会发现有人不同意这一点。别听他们的。
这是 Tkinter 中的一个示例。此示例适用于 python 2.x。对于 python 3.x,您需要从以下位置导入tkinter
而不是Tkinter
.
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
# create a prompt, an input box, an output label,
# and a button to do the computation
self.prompt = tk.Label(self, text="Enter a number:", anchor="w")
self.entry = tk.Entry(self)
self.submit = tk.Button(self, text="Submit", command = self.calculate)
self.output = tk.Label(self, text="")
# lay the widgets out on the screen.
self.prompt.pack(side="top", fill="x")
self.entry.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
def calculate(self):
# get the value from the input widget, convert
# it to an int, and do a calculation
try:
i = int(self.entry.get())
result = "%s*2=%s" % (i, i*2)
except ValueError:
result = "Please enter digits only"
# set the output widget to have our result
self.output.configure(text=result)
# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()