如何在tkinter中创建弹出窗口?

时间:2017-01-30 22:04:45

标签: python-3.x tkinter popup popupwindow

我在为程序创建弹出窗口时遇到问题。

代码:

from tkinter import *
from tkinter import ttk
import tkinter as tk

def popupBonus():
    popupBonusWindow = tk.Tk()
    popupBonusWindow.wm_title("Window")
    labelBonus = Label(popupBonusWindow, text="Input")
    labelBonus.grid(row=0, column=0)
    B1 = ttk.Button(popupBonusWindow, text="Okay", command=popupBonusWindow.destroy())
    B1.pack()

class Application(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        mainwindow = ttk.Frame(self)

        self.buttonBonus = ttk.Button(self, text="Bonuses", command=popupBonus)
        self.buttonBonus.pack()

代码生成一个带有按钮的窗口,当你按下按钮时,它应该生成一个标题为“Window”的弹出窗口,文本“Input”,并有一个按钮说“Okay”退出弹出窗口并返回到主窗口。但是,我收到了这个错误。

 Traceback (most recent call last):
  File "D:\Softwares\Python 3.6.0\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
  File "C:\Users\J---- M--\Desktop\Python\GUI-Messagebox 5.py", line 12, in popupBonus
B1 = ttk.Button(popupBonusWindow, text="Okay", command=popupBonusWindow.destroy())
  File "D:\Softwares\Python 3.6.0\lib\tkinter\ttk.py", line 614, in __init__
Widget.__init__(self, master, "ttk::button", kw)
  File "D:\Softwares\Python 3.6.0\lib\tkinter\ttk.py", line 559, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "D:\Softwares\Python 3.6.0\lib\tkinter\__init__.py", line 2293, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: NULL main window

我不知道问题是什么。我试图找到答案4个小时,基本上放弃了。

另外,我不想使用tkinter的消息框功能,因为我不想要感叹号图像,我希望稍后在弹出窗口中包含多个复选框。

1 个答案:

答案 0 :(得分:9)

我发现了3个错误

  • 使用Toplevel()代替Tk()创建第二个/第三个窗口
  • command=期望回调 - 没有()的函数名称 (但您使用popupBonusWindow.destroy()
  • 不要在一个窗口或框架中混合pack()grid() (但您在弹出窗口中使用grid()pack()

但您也可以使用内置消息框,例如showinfo()

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

def popup_bonus():
    win = tk.Toplevel()
    win.wm_title("Window")

    l = tk.Label(win, text="Input")
    l.grid(row=0, column=0)

    b = ttk.Button(win, text="Okay", command=win.destroy)
    b.grid(row=1, column=0)

def popup_showinfo():
    showinfo("Window", "Hello World!")

class Application(ttk.Frame):

    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.pack()

        self.button_bonus = ttk.Button(self, text="Bonuses", command=popup_bonus)
        self.button_bonus.pack()

        self.button_showinfo = ttk.Button(self, text="Show Info", command=popup_showinfo)
        self.button_showinfo.pack()

root = tk.Tk()

app = Application(root)

root.mainloop()