Python 在 Jupyter Notebook 中使用 Tkinter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45934942/
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
Using Tkinter in Jupyter Notebook
提问by sky_bird
I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
我刚刚开始使用 Tkinter 并尝试在 python 中创建一个简单的弹出框。我从网站上复制粘贴了一个简单的代码:
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop( )
This code is taking really long time to run, it has been almost 5 minutes! Is it not possible to just run this snippet? Can anybody tell me how to use Tkinter?
这段代码的运行时间真的很长,已经快 5 分钟了!不能只运行这个片段吗?谁能告诉我如何使用 Tkinter?
I am using jupyter notebook and python version 2.7. I would request a solution for this version only.
我正在使用 jupyter notebook 和 python 2.7 版。我只会请求此版本的解决方案。
采纳答案by DeathHyman
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.config(justify = CENTER)
entry1 = Entry(root, width = 30)
entry1.pack()
label3 = Label(root, text="Last Name")
label3.pack()
label1.config(justify = CENTER)
entry2 = Entry(root, width = 30)
entry2.pack()
button1 = Button(root, text = 'submit')
button1.pack()
button1.config(command = get_input)
root.mainloop()
Copy paste the above code into a editor, save it and run using the command,
将上面的代码复制粘贴到编辑器中,保存并使用命令运行,
python sample.py
Note: The above code is very vague. Have written it in that way for you to understand.
注意:上面的代码很模糊。已经这样写出来让你明白了。
回答by Aminu Kano
Your code is working just fine. Nevertheless for those using python3
module name has changed from Tkinter
to tkinter
all in lowercase. Edit the name and you're good to go!
您的代码运行良好。尽管如此,对于那些使用python3
模块名称的人来说Tkinter
,tkinter
所有的都变成了小写。编辑名称,您就可以开始了!
In a nutshell.
简而言之。
python2:
蟒蛇2:
from Tkinter import *
python3:
蟒蛇3:
from tkinter import *
Look at the screenshot below
看下面的截图
回答by matsbauer
You can create a popup information window as follow:
您可以创建一个弹出信息窗口,如下所示:
showinfo("Window", "Hello World!")
showinfo("Window", "Hello World!")
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
如果您想创建一个带有输入掩码的真实弹出窗口,您将需要生成一个新的 TopLevel 掩码并打开第二个窗口。
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.grid(row=0, column=0)
button = ttk.Button(win, text="Done", command=win.destroy)
button.grid(row=1, column=0)