如何让Tkinter MessageBox弹窗居中于根窗口而非屏幕
解决Tkinter类结构中MessageBox居中根窗口的问题
在类结构的Tkinter程序中,让messagebox弹窗居中根窗口的关键是给弹窗方法传入parent=self参数——因为你的App类继承自tk.Tk,self就是根窗口实例,弹窗会以此为基准居中显示。
你只需要修改两处messagebox调用的代码:
- 在
button_submit方法中:
messagebox.showinfo(title='Information', message='Success', parent=self)
- 在
add_to_file方法的异常处理中:
messagebox.showerror('Error', 'Log File Permission Denied!', parent=self)
修改后的完整代码如下:
import tkinter as tk from tkinter import ttk from tkinter import messagebox from datetime import date from openpyxl import load_workbook class App(tk.Tk): def __init__(self): super().__init__() # Configure the root window self.title('Profit Tool') self.geometry('300x220') # Details self.label = ttk.Label(self, text='Details:') self.label.pack() self.details = tk.Entry(self) self.details.pack() # Profit self.label = ttk.Label(self, text='Profit/Loss:') self.label.pack() self.profit = tk.Entry(self) self.profit.pack() self.label = ttk.Label(self, text='') self.label.pack() # Button self.button = ttk.Button(self, text='Submit', default='active', padding=5, command=self.button_submit) self.button.pack() def button_submit(self): self.add_to_file() self.clear_entries() messagebox.showinfo(title='Information', message='Success', parent=self) def add_to_file(self): # Read Content From File try: wb = load_workbook(filename="Tool Log.xlsx") ws = wb.active row = ws.max_row + 1 get_date = date.today() today = get_date.strftime('%d/%m/%y') # Format Date Cell cell = ws.cell(column=2, row=row) cell.number_format = 'dd/mm/yy;@' cell.value = today # Format Details Cell cell = ws.cell(column=5, row=row) cell.value = self.details.get() # Format Profit Cell cell = ws.cell(column=6, row=row) cell.number_format = '£#,##0.00' cell.value = float(self.profit.get()) wb.save("Tool Log.xlsx") wb.close() except PermissionError: messagebox.showerror('Error', 'Log File Permission Denied!', parent=self) raise Exception('Log File Permission Denied!') def clear_entries(self): self.details.delete(0, 'end') self.profit.delete(0, 'end') if __name__ == "__main__": app = App() app.mainloop()
内容的提问来源于stack exchange,提问作者Tom Hughes
相关产品推荐
相关产品推荐

