slacr_

Just to record my life and thoughts.
笔记/编程/杂乱/极简

[Python]GUI-tkinter

Sep 7, 2023Python446 words in 3 min

Tkinter

Tkinter是事实上的Python标准GUI工具包,包含在Python标准安装中. 除此之外还有其他GUI工具包

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-

from tkinter import *
def clicked():
print("hi")


mainloop()
btn = Button()
btn.pack()
btn['text'] = 'click me'
btn['command'] = clicked

布局

对控件调用方法pack时,将把控件放在其父控件(主控件)中。要指定主控件,可使用构造函数的第一个可选参数;如果没有指定,将把顶级主窗口用作主控件

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-

from tkinter import *

Label(text="first window").pack()
second = Toplevel()
Label(second, text="second window").pack()
mainloop()

# %%
help(Pack.config)
help(Grid.configure)
help(Place.config)

事件处理

可通过设置属性command给按钮指定动作(action)。这是一种特殊的事件处理,但Tkinter还提供了更通用的事件处理机制:方法bind。要让控件对特定的事件进行处理,可对其调用方法bind,并指定事件的名称和要使用的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-

from tkinter import *
top = Tk()


def callback(event):
print(event.x, event.y)


top.bind('<Button-1>', callback)
# <Button-1> 是鼠标左键单击事件
mainloop()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter.scrolledtext import ScrolledText


def load():
with open(filename.get()) as file:
contents.delete('1.0', END)
contents.insert(INSERT, file.read())


def save():
with open(filename.get(), 'w') as file:
file.write(contents.get('1.0', END))


top = Tk()
top.title("Simple Editor")
contents = ScrolledText()
contents.pack(side=BOTTOM, expand=True, fill=BOTH)

filename = Entry()
filename.pack(side=LEFT, expand=True, fill=X)

Button(text='Open', command=load).pack(side=LEFT)
Button(text='Save', command=save).pack(side=LEFT)

mainloop()
  1. Fluent Python
  2. python核心编程
  3. python基础教程第三版
  4. Python Packaging
  • Author:

    slacr_

  • Copyright:

  • Published:

    September 7, 2023

  • Updated:

    September 7, 2023

Buy me a cup of coffee ☕.

1000000