Python GUI编程(Tkinter)(一)

时间:2023-03-09 19:37:14
Python GUI编程(Tkinter)(一)

tk官网的教程学习: https://tkdocs.com/tutorial/firstexample.html

学习blog: https://www.cnblogs.com/aland-1415/p/6849193.html

创建一个GUI程序

1,导入 ,tkinter 模块

2,创建控件

3,指定这个控件的 master, 即这个控件属于哪一个

4,告诉 GM(geometry manager) 有一个控件产生了。

  • /dʒɪ'ɒmɪtrɪ/  几何管理器
#!/usr/bin/python
# -*- coding: UTF-8 -*- from tkinter import * # 导入 Tkinter 库 root = Tk()
# 创建两个列表
li = ['C', 'python', 'php', 'html', 'SQL', 'java']
movie = ['CSS', 'jQuery', 'Bootstrap']
listb = Listbox(root) # 创建两个列表组件
listb2 = Listbox(root)
for item in li: # 第一个小部件插入数据
listb.insert(0, item) for item in movie: # 第二个小部件插入数据
listb2.insert(0, item) listb.pack() # 将小部件放置到主窗口中
listb2.pack()
root.mainloop() # 进入消息循环

Python GUI编程(Tkinter)(一)

Tkinter 组件

Tkinter的提供各种控件,如按钮,标签和文本框,一个GUI应用程序中使用。这些控件通常被称为控件或者部件。

目前有15种Tkinter的部件。我们提出这些部件以及一个简短的介绍,在下面的表:

Python GUI编程(Tkinter)(一)

Python GUI编程(Tkinter)(一)

简单窗口的设置

import tkinter as tk

# 设置窗口
window = tk.Tk() # 建立一个窗口
window.title("Hello World")
window.geometry('300x200')# 窗口大小为300x200 var = tk.StringVar() # 文字变量存储器 #设置标签
l = tk.Label(textvar = var, bg = "blue", width = 20, height = 2) # 参数textvar不同于text,bg是backgroud
l.pack() # 放置标签 bon = False def hit_me(): # 该函数实现按一次按钮显示出字,再按一次字消失
global bon # bon为全局变量
if bon == False:
bon = True
var.set('hahahha')
else:
bon = False
var.set('') # 设置按钮
b = tk.Button(text='点击我有惊喜', width=20, height=2, command=hit_me)
b.pack() window.mainloop() # 循环,时刻刷新窗口

Python GUI编程(Tkinter)(一)

输入框和文本显示框

import tkinter as tk

# 设置窗口
window = tk.Tk() # 建立一个窗口
window.title("插入字符的窗口")
window.geometry('500x300') # 设置输入窗口
e = tk.Entry()
e.pack() # 该函数的功能是在光标处插入字符串
def insert_point():
var1 = e.get()
t.insert('insert', var1) # 参数insert表示在光标处插入字符串 # 该函数的功能是在光标处插入字符串
def insert_end():
var2 = e.get()
t.insert('end', var2) # 参数end表示在光标处插入字符串 # 设置两个插入按钮
b1 = tk.Button(text='在光标处插入', width=20, height=2, command=insert_point)
b1.pack()
b2 = tk.Button(text='在末尾处插入', width=20, height=2, command=insert_end)
b2.pack() # 设置文本显示框
t = tk.Text(width=20, height=2)
t.pack() window.mainloop() # 循环,时刻刷新窗口

Python GUI编程(Tkinter)(一)

https://www.runoob.com/python/python-gui-tkinter.html

https://blog.csdn.net/qq_41149269/article/details/81293772