[英]Python Tkinter module not showing output
我正在尝试学习 Python 并在 Python 中尝试一些 GUI 并遇到了这个 Tkinter 模块。 我的代码运行但我运行时没有出现窗口。 我的代码如下:
from Tkinter import *
#to create a root window
root = Tk()
程序运行,没有错误,但窗口不显示。
将此添加到您的代码root.mainloop()
,这是一个教程。
回应你的评论
#Also note that `from <module> import *` is generally frowned upon
#since it can lead to namespace collisions. It's much better to only
#explicitly import the things you need.
from Tkinter import Tk, Label
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
正如其他答案所指出的,您需要在根对象上调用mainloop
。
我推荐 OO 风格的编程,我也建议不要进行全局导入(即:不是“从 Tkinter 导入 *”)。
这是我通常开始使用的模板:
import Tkinter as tk
class ExampleView(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
l = tk.Label(self, text="your widgets go here...", anchor="c")
l.pack(side="top", fill="both", expand=True)
if __name__=='__main__':
root = tk.Tk()
view = ExampleView(root)
view.pack(side="top", fill="both", expand=True)
root.mainloop()
这样可以很容易地将您的主要逻辑保留在文件的开头,并将根的创建和mainloop
的调用mainloop
在一起,我认为这使代码更容易理解。 它还使重用此代码更容易一些(即:您可以创建一个更大的程序,其中这是可以创建的几个窗口之一)
最后添加root.mainloop()
。
试试这个 :
import tkinter as tk
window = tk.Tk()
# to show the window
window.mainloop()
from tkinter import*
root = Tk()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.