簡體   English   中英

如何在 tkinter 中創建彈出窗口?

[英]How do I create a popup window in tkinter?

我在為程序創建彈出窗口時遇到問題。

代碼:

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”的彈出窗口,並有一個按鈕說“好的”退出彈出窗口並返回主窗口. 但是,我收到此錯誤。

 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 的消息框功能,因為我不想要感嘆號圖像,並且我想稍后在彈出窗口中包含多個復選框。

我發現了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()

順便說一句:我把它放在頁面上: Tkinter:如何創建彈出窗口或消息框

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM