這篇文章主要介紹了Python: tkinter窗口屏幕居中,設置窗口最大,最小尺寸實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了。大家直接看代碼吧!
#!/usr/bin/env python
#coding=utf-8
'''
窗口屏幕居中,設置窗口最大,最小尺寸...
版權所有 2014 yao_yu (http://blog.csdn.net/yao_yu_126)
本代碼以MIT許可協議發佈
2014-04-15 創建
'''
import tkinter as tk
from tkinter import ttk
def get_screen_size(window):
return window.winfo_screenwidth(),window.winfo_screenheight()
def get_window_size(window):
return window.winfo_reqwidth(),window.winfo_reqheight()
def center_window(root, width, height):
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
print(size)
root.geometry(size)
root = tk.Tk()
root.title('測試窗口')
center_window(root, 300, 240)
root.maxsize(600, 400)
root.minsize(300, 240)
ttk.Label(root, relief = tk.FLAT, text = '屏幕大小(%sx%s)\n窗口大小(%sx%s)' % (get_screen_size(root) + get_window_size(root))).pack(expand = tk.YES)
tk.mainloop()
補充知識:關於tkinter幾個需要用到的窗口設置
設置窗口的大小和位置
geometry(widthxheight+x+y)
窗口的長寬分別爲width和height;
窗口到主窗口的間距爲 x和 y ;
注意可以使用減號,例如 10x10-10-10 代表10*10大小的窗口出現在右下角,但是不能直接使x或y爲負值,然後帶入 wxh+x+y;同時這個格式裏不能有空格。
當沒有參數時,用此方法能返回當前的尺寸位置參數。
# -*- coding:utf-8 -*-
from tkinter import *
root = Tk()
width, height, padx, pady = 800, 600, 40, 300
root.geometry('%dx%d-%d+%d' % (width, height, padx, pady))
設置窗口樣式、透明和全屏
-toolwindow 可設置窗口爲工具欄樣式;
-alpha 可設置透明度,0完全透明,1不透明。這裏透明是窗口內的所有內容,不僅是窗體,所以要特別小心一個完全透明的窗口!
-fullscreen 設置全屏 注意前面的短橫槓(-) 不能少
-topmost 設置窗口置頂。兩個同時被置頂的窗口爲同級(能互相遮蓋),但他們都能同時遮蓋住沒有被設置爲置頂的窗口。
root.attributes('-toolwindow', False,
'-alpha', 0.9,
'-fullscreen', True,
'-topmost', True)
思考題:一個全屏、置頂、透明、去標題欄的窗口將意味着什麼?
寫到這裏,給大家推薦一個資源很全的python學習聚集地,點擊進入,這裏有資深程序員分享以前學習
心得,學習筆記,還有一線企業的工作經驗,且給大家精心整理一份python零基礎到項目實戰的資料,
每天給大家講解python最新的技術,前景,學習需要留言的小細節
以上這篇Python: tkinter窗口屏幕居中,設置窗口最大,最小尺寸實例就是小編分享給大家的全部內容了