概观
不,你不必“画一个矩形,然后做一个循环”。你将需要做的是进口某种形式的GUI工具包,并使用内置在该工具包中的方法和对象。一般来说,其中一种方法是运行一个循环来监听事件并根据这些事件调用函数。此循环称为事件循环。因此,虽然必须运行这样的循环,但您不必创建循环。
注意事项
如果您希望从提示中打开一个窗口,例如您链接到的视频,则问题会更加严峻。这些工具包不是以这种方式使用的。通常,您编写一个完整的基于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()