一般来说,一个完整的tkinter程序就3个部分:
1. 导入模块部分
2. 生成窗体,创建组件并处理事件的相关代码
3. 维持窗体,等待事件发生的语句:mainloop
from tkinter import * # 使用 import 导入模块
root=Tk() # 建立一个名为root的窗体
#其它代码
root.mainloop() # 维持住窗体,等待事件的发生
这就可以生成一个主窗口,其他所有的控件,如按钮什么的都是在后来“贴”在root中的,但是,我们这里以面向对象的写法为主,因为相对于面向过程的写法,面向对象的写法在后期的维护方面有更大的优势。
import tkinter as tk
class Main(tk.Tk):
def __init__(self) -> None:
super().__init__()
# 其它代码
self.mainloop() #主循环一定要有,要不然不会显示。
if __name__ == "__main__":
main = Main()
大家自行运行下看看效果。
import tkinter as tk
class Main(tk.Tk):
def __init__(self) -> None:
super().__init__()
self.set_main_window()
self.mainloop() #主循环一定要有,要不然不会显示。
def set_main_window(self):
self.title("我的第一个窗体") #标题栏标题
self.geometry('300x500+800-200') #宽x高+左边距-下边距(x是小写英文单词,不是乘号,+和-对应窗口与屏幕边界的距离)
# self.iconbitmap('car.ico') #设置图标,有的系统不支持。
self.resizable(False,True) #(宽高)可调节的设置。
self.attributes("-topmost",True) # 窗口置顶
self.minsize(200,300) #窗口最小尺寸
self.maxsize(400,600) #窗口最大尺寸
self.iconify() #窗口最小化
self.deiconify() #取消最小化/取消隐藏
self.withdraw() # 窗体隐藏
self.deiconify()
#我们来让窗体居中
self.update()
self.x =(self.winfo_screenwidth()-300)/2 #winfo_screenwidth()返回屏幕的宽度
self.y = (self.winfo_screenheight()-500)/2 # winfo_screenwidth()返回屏幕的高度
self.geometry('+%d+%d'%(self.x,self.y))
print(self.cget('width'))
print(self.cget('height'))
if __name__ == "__main__":
main = Main()
# print(main.cget('width'))
0
0
以上部分可以自己尝试一下,一条一条运行代码看看效果,加深印象。
import tkinter as tk
class Main(tk.Tk):
def __init__(self) -> None:
super().__init__()
self.set_keys()
self.mainloop() #主循环一定要有,要不然不会显示。
def set_keys(self):
"""kyes()是窗体的属性,可以打印出来"""
print(self.keys())
# 设置keys有两种方法,下面是第一种
self['borderwidth'] = 3
self['background'] = 'lightblue' #设置背景色
self['cursor'] = 'hand2'
# 下面是第二种,用哪一种方法都可以
self.config(borderwidth=2,background='lightblue',cursor='hand2',height=300,width=300)
# 获取属性也有两种方法,第一种:
print(self['cursor'])
# 第二种
print(self.cget('cursor'))
print(self.cget('height')) #如果没有用config设置过height和width,那么cget到的数据是0。
if __name__ == "__main__":
main = Main()
['bd', 'borderwidth', 'class', 'menu', 'relief', 'screen', 'use', 'background', 'bg', 'colormap', 'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'takefocus', 'visual', 'width']
hand2
hand2
300
因篇幅问题不能全部显示,请点此查看更多更全内容