0
点赞
收藏
分享

微信扫一扫

【Python】用三种方法创建tkinter桌面窗口

Python的tkinter是Python的标准GUI库之一,它是一个开源的、跨平台的GUI工具包,可以用于创建桌面应用程序。

tkinter提供了许多常见的GUI组件,例如按钮、文本框、标签、列表框等等,可以轻松地创建各种类型的桌面应用程序。它还支持各种操作系统,包括Windows、Linux和macOS。

使用tkinter,你可以在Python代码中创建GUI元素,并对它们进行配置、事件处理和操作。你可以使用各种布局管理器来排列GUI组件,并使用回调函数来响应用户的输入事件。

tkinter是一个强大而灵活的GUI工具包,可以帮助你快速地创建各种类型的桌面应用程序。

第一种:

import tkinter as tk

root = tk.Tk() # 创建窗口
root.title('自定义标题') # 窗口标题
root.geometry('300x200') # 窗口像素大小
root.mainloop() # 循环主窗口

运行结果

第二种:

import tkinter as tk

class Window:
"""创建桌面窗口"""

def __init__(self):
"""构造方法"""

root = tk.Tk() # 创建窗口
root.title('自定义标题') # 窗口标题
root.geometry('300x200+400+200') # 窗口像素大小(300x200)及显示位置(400+200)

# 文本域
self.text = tk.Text(root, background='pink', font=('Tahoma', 16))
self.text.pack(fill=tk.BOTH, expand=True)
self.text.bind('<KeyRelease>', self.getTextData)

root.mainloop() # 循环主窗口

# 获取文本域数据
def getTextData(self, event=None):
print([self.text.get('1.0', tk.END)])


ui = Window() # 实例化对象

运行结果

第三种:

import tkinter as tk
from tkinter import ttk

class Window(tk.Tk):
"""继承tkinter.Tk()方法,创建桌面窗口"""

def __init__(self):
"""构造方法"""

super().__init__() # 调用父类(Tk)的构造方法(等价于root = tk.Tk())
self.title('自定义标题') # 窗口标题
self.geometry('400x300+400+200') # 窗口像素大小(400x300)及显示位置(400+200)

# 新窗口
self.button = tk.Button(self, text='新窗口', command=self.newWindow)
self.button.pack(side=tk.BOTTOM)

# 文本域
self.text = tk.Text(self, background='pink', font=('Tahoma', 16))
self.text.pack(fill=tk.BOTH, expand=True)
self.text.bind('<KeyRelease>', self.getTextData) # 捆绑按键释放事件
self.text.focus_set() # 设置焦点

# 新窗口
def newWindow(self, event=None):
self.newWin = tk.Toplevel() # 创建新窗口
self.newWin.title('自定义标题') # 窗口标题
self.newWin.geometry('300x200+450+240') # 窗口像素大小(300x200)及显示位置(450+240)
self.newWin.focus_set() # 设置焦点

# 标签
self.dataLabel = ttk.Label(self.newWin, text=self.text.get('1.0', tk.END), anchor='nw', relief=tk.GROOVE)
self.dataLabel.pack(fill=tk.BOTH, expand=True)

# 关闭
self.closeButton = ttk.Button(self.newWin, text='关闭', command=self.newWin.destroy)
self.closeButton.pack(side=tk.BOTTOM)


# 获取文本域数据
def getTextData(self, event=None):
print([self.text.get('1.0', tk.END)])


ui = Window() # 对象实例化
ui.mainloop() # 循环窗口

运行结果

作者:周华

创作日期:2023/11/26

举报

相关推荐

0 条评论