如何在python中制作带有按钮的窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22108738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a window with buttons in python
提问by user2874724
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?
我是否必须创建一个窗口,在其中绘制一个带有字符串的矩形,然后创建一个循环来检查鼠标移动/鼠标点击,然后在鼠标坐标位于其中一个按钮内时返回一些东西,并且鼠标被点击了?或者是否有一个功能/一组功能可以使带有按钮的窗口更容易?还是模块?
采纳答案by Bryan Oakley
Overview
概述
No, you don't have to "draw a rect, then make a loop". What you willhave 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.
不,您不必“绘制矩形,然后进行循环”。你将需要做的是进口某种形式的GUI工具包,并使用方法和对象的内置到该工具包。一般来说,其中一种方法是运行一个循环,该循环侦听事件并根据这些事件调用函数。这个循环称为事件循环。因此,虽然必须运行这样的循环,但您不必创建循环。
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.
如果您希望从提示(例如您链接到的视频)中打开一个窗口,则问题会更棘手一些。这些工具包并非旨在以这种方式使用。通常,您编写一个完整的基于 GUI 的程序,其中所有输入和输出都通过小部件完成。这并非不可能,但在我看来,学习时应该坚持使用所有文本或所有 GUI,而不是将两者混合。
Example using Tkinter
使用 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.
例如,一个这样的工具包是 tkinter。Tkinter 是 Python 内置的工具包。任何其他工具包(例如 wxPython、PyQT 等)都非常相似,并且也能正常工作。Tkinter 的优势在于您可能已经拥有它,它是学习 GUI 编程的绝佳工具包。这对于更高级的编程也很棒,尽管您会发现有人不同意这一点。不要听他们的。
Here's an example in Tkinter. This example works in python 2.x. For python 3.x you'll need to import from tkinterrather than Tkinter.
这是 Tkinter 中的一个示例。此示例适用于 python 2.x。对于 python 3.x,您需要导入 fromtkinter而不是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()
回答by Chigurh
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.
回答by Kunal Munjal
#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.
这是最基本的。
回答by SporkX
Here is my method, to create a window with a button called "Hello!" and when that is closed, a new window opens with "Cool!"
这是我的方法,创建一个带有名为“Hello!”的按钮的窗口。当它关闭时,一个新窗口打开,“酷!”
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)
回答by Ieshaan Saxena
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()

