本文共 1887 字,大约阅读时间需要 6 分钟。
本文将详细介绍如何使用Tkinter实现窗口编程的种种操作,包括窗口设置、控件管理以及实际代码编制方法。通过多个示例代码展示窗口开发流程,并分析实现效果。
窗口的创建与展示可以通过Tk()和mainloop()函数完成。程序的主要逻辑应附着在窗口内部部件上。
窗口内容是实现GUI应用的关键部分,主要包括:
设置窗口尺寸可以通过以下方法实现:
要设置窗口位置,需先获取屏幕尺寸:
以下代码展示了如何将窗口居中显示:
from tkinter import Tkroot = Tk()root.title('Python GUI Learning')width = 380height = 300screenwidth = root.winfo_screenwidth()screenheight = root.winfo_screenheight()alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)//2, (screenheight-height)//2)root.geometry(alignstr)root.resizable(width=False, height=True)root.mainloop() Tkinter 提供多种控件,如按钮、标签、文本框等。常用控件及其管理方法包括:
标签控件是GUI应用的基础,常见用法包括:
通过PhotoImage加载图片并显示:
from tkinter import *root = Tk()root.title('Python GUI Learning')logo = PhotoImage(file='temp.gif')Label(root, image=logo).pack(side='left')root.mainloop() 实现标签中的文字与图片混合显示:
from tkinter import *root = Tk()root.title('Python GUI Learning')logo = PhotoImage(file='skyeL2.gif')Label(root, compound=CENTER, text="描述文字", image=logo).pack(side='right')root.mainloop() 转载地址:http://bnofk.baihongyu.com/