我试图创建一个弹出消息,它总是说popupmsg没有被定义,它应该怎么办?

时间:2017-10-28 20:22:29

标签: python python-3.x

from tkinter import *
import math

NORM_FONT = ("Ariel", 12)


class window(object):  # An object has been created called window
    def __init__(self, root):  # The function root has been initialised

        self.root = root  # This gives root and attribute
        self.root.title("Calculator")
        menu = Menu(self.root)
        self.root.config(menu=menu)
        file = Menu(menu)
        file.add_command(label="Save", command=self.save_calc)
        menu.add_cascade(label="File", menu=file)
        edit = Menu(menu)
        edit.add_command(label="Change Calc")
        menu.add_cascade(label="Edit", menu=edit)
        file.add_command(label="Save Settings", command=lambda: popupmsg("A text file has been created in the directory"))

    def save_calc(self):  # This save calc method will allow the user to save the calculation they have written
        f = open("Untitled", "w")  # opens a file with a untitled.txt
        self.Save = f.write("Write your previous calculation")
        self.Save = f.close()  # This closes the file

    def popupmsg(msg=""):
        popup = tk.Tk()
        popup.wm_title("!")
        label = tk.Label(popup, text=msg, font=NORM_FONT)
        label.pack(side="top", fill="x", pady=10)
        b1 = tk.Button(popup, text="Okay", command=popup.destroy)
        b1.pack()
        popup.mainloop()


screen = Tk()
window(screen)
screen.geometry("700x400")
screen.mainloop()

print("Hello World")

1 个答案:

答案 0 :(得分:0)

首先,您必须修复方法popupmsg以添加self参数,并实例化TopLevel而不是第二个Tk()(并删除所有{{}} {1}}这里没有在您的导入中定义)

tk.

然后你可以使用def popupmsg(self, msg=""): popup = Toplevel(self.root) popup.wm_title("!") label = Label(popup, text=msg, font=NORM_FONT) label.pack(side="top", fill="x", pady=10) b1 = Button(popup, text="Okay", command=popup.destroy) b1.pack() # mainloop is not needed here

在lambda中调用此方法
self.popupmsg