Python-GUI实现图形窗口居中

核心代码

def windowCenter(self,width,height):
    screenwidth = self.window.winfo_screenwidth()
    screenheight = self.window.winfo_screenheight()
    size = "%dx%d+%d+%d"%(width,height,screenwidth/2-width/2,screenheight/2-height/2)
    self.window.geometry(size)

完整代码

import tkinter as tk




class MainWindow():
  def __init__(self):
    # 创建主窗口
    self.window = tk.Tk()
    self.window.minsize(800, 750)
    self.windowCenter(800,750)
    self.window.title("连连看小游戏")
    # 添加组件
    self.addComponents()

    # 进入消息循环
    self.window.mainloop()

  def windowCenter(self,width,height):
    screenwidth = self.window.winfo_screenwidth()
    screenheight = self.window.winfo_screenheight()
    size = "%dx%d+%d+%d"%(width,height,screenwidth/2-width/2,screenheight/2-height/2)
    self.window.geometry(size)

  def addComponents(self):
    my_frame = tk.Frame(self.window)
    my_frame.pack(side=tk.TOP)

    # 创建按钮
    my_button = tk.Button(my_frame, text="连连看小游戏")
    my_button.pack(side=tk.LEFT)

    # 创建Canvas
    my_canvas = tk.Canvas(my_frame, bg='white')
    my_canvas.create_rectangle(50, 50, 150, 150, outline='red', fill='blue', width=5)

    # # 创建复选框
    # my_apple = tk.Checkbutton(my_frame, text='苹果')
    # my_apple.pack(side=tk.TOP)
    #
    # # 创建单行文本
    # name = tk.Label(my_frame, text="姓名")
    # name.pack(side=tk.LEFT)
    # name_value = tk.Entry(my_frame, bd=5)
    # name_value.pack(side=tk.RIGHT)


if __name__ == "__main__":
  MainWindow()








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值