我一直到处寻找是否可以找到任何帮助并且没有到任何地方 我的程序是一个简单的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)`
如果需要任何额外的代码,请告诉我,谢谢。
答案 0 :(得分:0)
您将需要构建一个自定义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()
结果:
我个人将全部构建在一个继承自Tk()
的类中,甚至使用ttk按钮制作按钮,并使用标签来引用位于::tk::icons::question
的内置问题图像,如下所示:>
import tkinter as tk
import tkinter.ttk as ttk
# import Tkinter as tk # for Python 2.X
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("300x224")
self.resizable(0, 0)
self.protocol("WM_DELETE_WINDOW", self.exit_window)
def yes_exit(self):
print("do other stuff here then self.destroy")
self.destroy()
def exit_window(self):
top = tk.Toplevel(self)
top.details_expanded = False
top.title("Quit")
top.geometry("300x100+{}+{}".format(self.winfo_x(), self.winfo_y()))
top.resizable(False, False)
top.rowconfigure(0, weight=0)
top.rowconfigure(1, weight=1)
top.columnconfigure(0, weight=1)
top.columnconfigure(1, weight=1)
tk.Label(top, image="::tk::icons::question").grid(row=0, column=0, pady=(7, 0), padx=(7, 7), sticky="e")
tk.Label(top, text="Are you sure you want to quit?").grid(row=0, column=1, columnspan=2, pady=(7, 7), sticky="w")
ttk.Button(top, text="OK", command=self.yes_exit).grid(row=1, column=1, sticky="e")
ttk.Button(top, text="Cancel", command=top.destroy).grid(row=1, column=2, padx=(7, 7), sticky="e")
if __name__ == "__main__":
GUI().mainloop()
结果: