简体   繁体   English

如何在python中制作带有按钮的窗口

[英]How to make a window with buttons in python

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.类似于此视频中的@ 3:05 https://www.khanacademy.org/science/computer-science-subject/computer-science/v/writing-a-simple-factorial-program---python-2 (我知道这是一个非常简单的初学者程序的教程,但它是我能找到的唯一视频)但没有文本框,而且我对“确定”和“取消”按钮的作用有更多的控制。

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.需要做的是进口某种形式的GUI工具包,并使用方法和对象的内置到该工具包。 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.通常,您编写一个完整的基于 GUI 的程序,其中所有输入和输出都通过小部件完成。 It's not impossible, but in my opinion, when learning you should stick to all text or all GUI, and not mix the two.这并非不可能,但在我看来,学习时应该坚持使用所有文本或所有 GUI,而不是将两者混合。

Example using Tkinter使用 Tkinter 的示例

For example, one such toolkit is tkinter.例如,一个这样的工具包是 tkinter。 Tkinter is the toolkit that is built-in to python. Tkinter 是 Python 内置的工具包。 Any other toolkit such as wxPython, PyQT, etc will be very similar and works just as well.任何其他工具包(例如 wxPython、PyQT 等)都非常相似,并且也能正常工作。 The advantage to Tkinter is that you probably already have it, and it is a fantastic toolkit for learning GUI programming. Tkinter 的优势在于您可能已经拥有它,它是学习 GUI 编程的绝佳工具包。 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.这是 Tkinter 中的一个示例。 This example works in python 2.x.此示例适用于 python 2.x。 For python 3.x you'll need to import from tkinter rather than Tkinter .对于 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()

You should take a look at wxpython , a GUI library that is quite easy to start with if you have some python knowledge.你应该看看wxpython ,如果你有一些 Python 知识,它是一个很容易开始的 GUI 库。

The following code will create a window for you ( source ):以下代码将为您创建一个窗口( 源代码):

import wx

app = wx.App(False)  # Create a new app, don't redirect stdout/stderr to a window.
frame = wx.Frame(None, wx.ID_ANY, "Hello World") # A Frame is a top-level window.
frame.Show(True)     # Show the frame.
app.MainLoop()

Take a look at this section (how to create buttons).看看这个部分(如何创建按钮)。 But start with the installation instructions .但从安装说明开始。

Here's my part.这是我的部分。 I'm making an AI chatbot, just working on the interface of logging in and sketching out stuff.我正在制作一个人工智能聊天机器人,只是在登录和勾画东西的界面上工作。 I'm also a beginner in .json so this helped me learn.我也是 .json 的初学者,所以这有助于我学习。

I'll also explain it maybe.也许我也会解释一下。

First, create a .json file named anything you'd like.首先,创建一个.json文件,命名为您喜欢的任何名称。 Make sure the file is in the same directory path/folder as the code, or you can import os to do that.确保文件与代码位于同一目录路径/文件夹中,或者您可以导入 os 来执行此操作。

Next import Tkinter.接下来导入 Tkinter。 It may or may not be an in-built module but try it and see.它可能是也可能不是内置模块,但请尝试并查看。 Also import JSON, time isn't required but can help.还导入 JSON,时间不是必需的,但可以提供帮助。

import tkinter as tk
import json
import time

Next, create a window for all this to happen.接下来,为所有这些发生创建一个窗口。 Edit the info if necessary.如有必要,编辑信息。

app = tk.Tk()
app.wm_title("Sign Up or Log in")
app.geometry("500x300")

Add a label if you want.如果需要,请添加标签。

k = tk.Label(text = "Hello there, I'm Lola! We'll talk soon. Just let me know your credentials!\nJust click on sign up below so that I can identify you!", justify="left")
k.pack()

Add a button for the user to click.添加一个按钮供用户单击。

sign_in = tk.Button(text="Sign Up or Log In", command=signin)
sign_in.pack()

We need to define the signing function used above for the button.我们需要为按钮定义上面使用的签名函数。 So before we create the button, we define it.所以在我们创建按钮之前,我们先定义它。 It's a bit long so I'll just explain the general parts.有点长,所以我只解释一般部分。 We first get their details before we check it在我们检查之前,我们首先获取他们的详细信息

def signin():
em = tk.Label(text="Email:")
em.pack()
en1 = tk.Entry(width=50)
en1.pack()
pa = tk.Label(text="Password:")
pa.pack()
en2 = tk.Entry(width=50)
en2.pack()
na = tk.Label(text="Name:")
na.pack()
en3 = tk.Entry(width=50)
en3.pack()

Next, let's define the submit function and create the button.接下来,让我们定义提交函数并创建按钮。 This is where json comes in. We first get the details and store them in a variable like so.这就是 json 的用武之地。我们首先获取详细信息并将它们存储在像这样的变量中。

def submit():
    email = str(en1.get())
    password = str(en2.get())
    name = str(en3.get())
    login = tk.Label(text="")

Then, we shouldn't forget to read the json file first然后,我们不应该忘记先读取json文件

with open("info.json", "r") as f:
        users = json.load(f)

Now let's do the checking现在让我们做检查

if email in users:
        login.config(text="You already have an account! Click log in please!")
        loginn = tk.Button(text = "Log in", command = login)
    else:
        users[email] = {}
        users[email]["Password"] = password
        users[email]["Name"] = name
        with open("info.json", "w") as f:
            json.dump(users, f)
        login.config(text=f"You've successfully created an account. Just click on log in below! Credentials:\nEmail: {email}\nPassword: {password}\nName: {name}")
    login.pack()

Now, we shall define login.现在,我们将定义登录。 Everything is pretty much similar一切都非常相似

def loggin():
    email = str(en1.get())
    password = str(en2.get())
    name = str(en3.get())
    login = tk.Label(text="")
    with open("info.json", "r") as f:
        users = json.load(f)
    if not email in users:
        login.config(text="You don't have an account, sign up instead!")
    else:
        passs = users[email]["Password"]
        if password != passs:
            login.config(text="Wrong credentials. It doesn't match what I've recorded")
        else:
            login.config(text="Success! You've logged in. Please wait, as the software is still in the early stage of development.\nYou might have to sign up again later. I'll let you know soon.")
    login.pack()
loginn = tk.Button(text = "Log in", command = loggin)
loginn.pack()

At the end, this one line of code will determine whether everything is going to work.最后,这一行代码将确定是否一切正常。 Make sure to put it in your code at the end.确保将其放在最后的代码中。

window.mainloop()

And that is the end, please don't copy this, I worked for 5 hours to understand this.这就是结束,请不要复制这个,我工作了 5 个小时来理解这一点。 I'm a beginner just like everyone else, but please do not copy this.我是一个初学者,就像其他人一样,但请不要复制此。 Use it as an example to understand.举个例子来理解。 Even if you do, please give credit.即使你这样做,请给予信任。 But mostly, don't.但大多数情况下,不要。

#Creating a GUI for entering name
def xyz():
    global a
    print a.get() 
from Tkinter import *
root=Tk()  #It is just a holder
Label(root,text="ENter your name").grid(row=0,column=0) #Creating label
a=Entry(root)           #creating entry box
a.grid(row=7,column=8)
Button(root,text="OK",command=xyz).grid(row=1,column=1)
root.mainloop()           #important for closing th root=Tk()

This is the basic one.这是最基本的。

tkinter is a GUI Library, this code creates simple no-text buttons: tkinter 是一个 GUI 库,这段代码创建了简单的无文本按钮:

 import tkinter as tk
 class Callback:
     def __init__(self, color):
         self.color = color
     def changeColor(self): 
         print('turn', self.color)
 c1 = Callback('blue')
 c2 = Callback('yellow')
 B1 = tk.Button(command=c1.changeColor) 
 B2 = tk.Button(command=c2.changeColor) 
 B1.pack()
 B2.pack()

Here is my method, to create a window with a button called "Hello!"这是我的方法,创建一个带有名为“Hello!”的按钮的窗口。 and when that is closed, a new window opens with "Cool!"当它关闭时,一个新窗口打开,“酷!”

from tkinter import *
def hello(event):
    print("Single Click, Button-l") 
def Cool(event):                           
    print("That's cool!")

widget = Button(None, text='Hello!')
widget.pack()
widget.bind('<Button-1>', Hello)
widget.mainloop()

widget = Button(None, text='Cool!')
widget.pack()
widget.bind('<Double-1>', Cool)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM