我正在尝试学习Python并在Python中尝试使用GUI,并遇到了这个Tkinter模块。我的代码运行但运行时窗口没有出现。我的代码如下
#GUI
#from Tkinter import *
from Tkinter import *
#to create a root window
root = Tk()
对此有任何帮助将不胜感激。程序运行,没有错误,但从/窗口没有显示
答案 0 :(得分:8)
将其添加到您的代码root.mainloop()
,Here's a tutorial。
回复您的评论
#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()
答案 1 :(得分:3)
正如其他答案所指出的那样,您需要在根对象上调用mainloop
。
我推荐使用OO风格的编程,我还建议不进行全局导入(例如: not '来自Tkinter import *')。
这是我通常从以下开始的模板:
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
的调用,我认为这使得代码更容易理解。它还使这个代码更容易重用(即:你可以创建一个更大的程序,这是可以创建的几个窗口之一)
答案 2 :(得分:0)
最后添加root.mainloop()
。
答案 3 :(得分:0)
试试这个:
import tkinter as tk
window = tk.Tk()
# to show the window
window.mainloop()