use*_*724 7 python user-input module window button
如何创建一个带有两个按钮的窗口的函数,其中每个按钮都有一个指定的字符串,如果单击该按钮,则返回一个指定的变量?类似@在这个视频3:05 https://www.khanacademy.org/science/computer-science-subject/computer-science/v/writing-a-simple-factorial-program---python-2我(知道它是一个非常简单的初学者程序的教程,但它是我能找到的唯一视频)但没有文本框,我对"确定"和"取消"按钮的操作有更多的控制.
我是否必须创建一个窗口,在其中绘制一个带有字符串的矩形,然后创建一个检查鼠标移动/鼠标单击的循环,然后在鼠标坐标位于其中一个按钮内部后返回一些内容,点击鼠标?或者是否有一个函数/函数集可以使按钮窗口更容易?还是一个模块?
Bry*_*ley 14
概观
不,你不必"画一个矩形,然后做一个循环".你将需要做的是进口某种形式的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()
Run Code Online (Sandbox Code Playgroud)