Skip to content

1.1认识tkinter

列出tkinter版本号

python
from tkinter import *

print(TkVersion)

1.2创建窗口

创建空白窗口,窗口默认名称是tk

python
from tkinter import *

root = Tk()
root.mainloop()

1.3窗口属性的设置

设置窗口标题、大小和背景颜色

python
from tkinter import *

root = Tk()
root.title("MyWindow")      # 窗口标题
root.geometry("300x160")    # 窗口大小
root.configure(bg='yellow') # 窗口背景颜色
root.mainloop()

更改系统默认的图标

python
from tkinter import *

root = Tk()
root.configure(bg='#00ff00')    # 窗口背景颜色
root.iconbitmap("mystar.ico")   # 更改图示
root.mainloop()

1.4窗口位置的设置

python
from tkinter import *

root = Tk()
root.geometry("300x160+400+200")     # 距离屏幕左上角(400,200)
root.mainloop()

另一种写法

python
from tkinter import *

root = Tk()
w = 300     # 窗口宽
h = 160     # 窗口高
x = 400     # 窗口左上角x轴位置
y = 200     # 窗口左上角Y轴位置
root.geometry("%dx%d+%d+%d" % (w,h,x,y))
root.mainloop()

窗口放在屏幕中央

python
from tkinter import *

root = Tk()
screenWidth = root.winfo_screenwidth()      # 屏幕宽度
screenHeight = root.winfo_screenheight()    # 屏幕高度
w = 300                                     # 窗口宽
h = 160                                     # 窗口高
x = (screenWidth - w) / 2                   # 窗口左上角x轴位置
y = (screenHeight - h ) / 2                 # 窗口左上角Y轴位置
root.geometry("%dx%d+%d+%d" % (w,h,x,y))
root.mainloop()