工具类
import tkinter as tk
from tkinter import Widget, Label
class SimpleWindow:
def __init__(self, title, width, height):
self.root = tk.Tk()
self.root.resizable(False, False)
self.root.title(title)
self.center_window(width, height)
def center_window(self, width, height):
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
x = (screen_width - width) // 2
y = (screen_height - height) // 2
self.root.geometry(f'{width}x{height}+{x}+{y}')
def add(self, target: Widget, x, y, w, h):
target.place(x=x, y=y, width=w, height=h)
def show(self):
self.root.mainloop()
示例代码
窗口400x300居中,组件100x100位于(100,100)处。
if __name__ == '__main__':
window = SimpleWindow("小游戏", 400, 300)
b = Label(window.root, text="你好,世界!", bg="red")
window.add(b, 100, 100, 100, 100)
window.show()
效果: