如何使用tkin设置MessageBox的位置

2024-10-02 20:38:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我到处找,想看看能不能帮上忙,但一直没找到 我的程序是一个简单的tkinter菜单,设置为屏幕左上角的默认位置,但是当我按下X按钮时,它会在屏幕中央加载消息框。在

如何使其将消息框捕捉到角落?在

root = Tk()
root.geometry('%dx%d+%d+%d' % (300, 224, 0, 0))
root.resizable(0,0)
def exitroot():
    if tkMessageBox.askokcancel("Quit", "Are you sure you want to quit?"):
        with open(settings, 'wb') as csvfile:
            writedata = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            writedata.writerow([setpass])
            writedata.writerow([opcolour] + [bkcolour])
            writedata.writerow([menu_background_status] + [menu_internet_status])
        root.destroy()
root.protocol("WM_DELETE_WINDOW", exitroot)`

如果需要额外的代码,请让我知道,并提前感谢。在


Tags: csvcsvfile程序you消息屏幕tkinterstatus
1条回答
网友
1楼 · 发布于 2024-10-02 20:38:46

您需要构建一个自定义的Toplevel()窗口,然后告诉它重新定位到根窗口的一角。我们可以用Toplevel()类和winfo()方法来实现这一点。在

import tkinter as tk
# import Tkinter as tk # for Python 2.X


class MessageWindow(tk.Toplevel):
    def __init__(self, title, message):
        super().__init__()
        self.details_expanded = False
        self.title(title)
        self.geometry("300x75+{}+{}".format(self.master.winfo_x(), self.master.winfo_y()))
        self.resizable(False, False)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        tk.Label(self, text=message).grid(row=0, column=0, columnspan=3, pady=(7, 7), padx=(7, 7), sticky="ew")
        tk.Button(self, text="OK", command=self.master.destroy).grid(row=1, column=1, sticky="e")
        tk.Button(self, text="Cancel", command=self.destroy).grid(row=1, column=2, padx=(7, 7), sticky="e")

root = tk.Tk()
root.geometry("300x224")
root.resizable(0, 0)

def yes_exit():
    print("do other stuff here then root.destroy")
    root.destroy()

def exit_root():
    MessageWindow("Quit", "Are you sure you want to quit?")

root.protocol("WM_DELETE_WINDOW", exit_root)
root.mainloop()

结果:

enter image description here

就我个人而言,我会构建继承自Tk()的多功能类,使按钮与ttk按钮相同,并使用标签引用位于::tk::icons::question的内置问题图像,如下所示:

^{pr2}$

结果:

enter image description here

相关问题 更多 >