如何在python中制作带有按钮的窗口 [英] How to make a window with buttons in python

查看:946
本文介绍了如何在python中制作带有按钮的窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个使窗口具有两个按钮的函数,其中每个按钮都有一个指定的字符串,如果单击该按钮,将返回一个指定的变量?类似于此视频中的@ 3:05

我是否必须创建一个窗口,在其中绘制一个带有矩形的rect,然后创建一个循环来检查鼠标的移动/鼠标单击,然后在鼠标坐标位于其中一个按钮内部时返回一些内容,然后单击鼠标? 还是有一个功能/一组功能会使带有按钮的窗口更容易?还是模块?

概述

不,您不必绘制矩形,然后进行循环".您要做的是导入某种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()

How do I create a function that makes a window with two buttons, where each button has a specified string and, if clicked on, returns a specified variable? Similar to @ 3:05 in this video https://www.khanacademy.org/science/computer-science-subject/computer-science/v/writing-a-simple-factorial-program---python-2 (I know it's a tutorial for a very easy beginners program, but it's the only video I could find) but without the text box, and I have more controls over what the 'ok' and 'cancel' buttons do.

Do I have to create a window, draw a rect with a string inside of it, and then make a loop that checks for mouse movement/mouse clicks, and then return something once the mouse coords are inside of one of the buttons, and the mouse is clicked? Or is there a function/set of functions that would make a window with buttons easier? Or a module?

解决方案

Overview

No, you don't have to "draw a rect, then make a loop". What you will have to do is import a GUI toolkit of some sort, and use the methods and objects built-in to that toolkit. Generally speaking, one of those methods will be to run a loop which listens for events and calls functions based on those events. This loop is called an event loop. So, while such a loop must run, you don't have to create the loop.

Caveats

If you're looking to open a window from a prompt such as in the video you linked to, the problem is a little tougher. These toolkits aren't designed to be used in such a manner. Typically, you write a complete GUI-based program where all input and output is done via widgets. It's not impossible, but in my opinion, when learning you should stick to all text or all GUI, and not mix the two.

Example using Tkinter

For example, one such toolkit is tkinter. Tkinter is the toolkit that is built-in to python. Any other toolkit such as wxPython, PyQT, etc will be very similar and works just as well. The advantage to Tkinter is that you probably already have it, and it is a fantastic toolkit for learning GUI programming. It's also fantastic for more advanced programming, though you will find people who disagree with that point. Don't listen to them.

Here's an example in Tkinter. This example works in python 2.x. For python 3.x you'll need to import from tkinter rather than 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()

这篇关于如何在python中制作带有按钮的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆