📓
Study
  • README
  • Application
    • Contest
      • 竞赛trick
  • Basic Know
    • 半监督学习
    • 贝叶斯
      • 朴素贝叶斯分类器
    • 对抗训练
    • 概率图模型
      • CRF
      • HMM
      • 概率图模型
    • 关联分析
    • 归纳偏置
      • [什么是 Inductive bias(归纳偏置)?](BasicKnow/归纳偏置/什么是 Inductive bias(归纳偏置)?.md)
    • 聚类
    • 决策树
    • 绿色深度学习
    • 树模型&集成学习
      • 提升树
      • Ada Boost
      • [集成学习]
    • 特征工程
      • 数据分桶
      • 特征工程概述
      • 特征选择
      • LDA
      • PCA
    • 线性模型
      • 感知机
      • 最大熵模型
      • SVM
        • SVM支持向量机
      • 逻辑回归
      • 线性回归
    • 优化算法
      • 拉格朗日对偶性
      • 牛顿法
        • 牛顿法&拟牛顿法
      • 梯度下降法
        • 梯度下降算法
      • 优化算法
    • 预处理
      • [1-1]正则表达式
      • [1-2]文本预处理
      • [1-3]词性
      • [1-4]语法分析
      • [1-6]文本分类
      • [1-7]网络爬取
      • 【备用】正则表达式
      • 7.re模块
      • 词典匹配
      • 分词
      • 子表达式
      • Todo
    • 主题模型
      • LDA
    • Deep Learning
      • 反向传播
      • 梯度消失&梯度爆炸
      • Batch Size
      • 1.DLbasis
      • 小概念
      • MLstrategy
      • CNN
      • RNN及其应用
      • 关于深度学习实践
      • 神经网络概述
      • Batch Normalization
      • Program CNN
      • Program D Lbasis
      • Program DN Nimprove
      • Program Neural Style Transfer
      • Summer DL
    • EM算法
    • GAN
      • Gans In Action Master
    • GNN
      • 搜广推之GNN
      • Representation Learning
        • Anomalydetection
        • Conclusion
        • Others
        • Papernotes
        • Recommadation
    • k近邻法
      • K近邻
    • Language Model
      • 语言模型解码采样策略
      • [1-1][语言模型]从N-gram模型讲起
      • [1-2][语言模型]NNLM(神经网络语言模型)
      • [1-3][语言模型]基于RNN的语言模型
      • [1-4][语言模型]用N-gram来做完形填空
      • [1-5][语言模型]用KenLM来做完形填空
    • Loss Function
      • 常用损失函数
      • Focal Loss
      • softmax+交叉熵
    • Machine Learning
      • [基础]概念
      • 待整合
      • 交叉验证
      • 无监督学习
      • 优缺点
      • ML Yearning
      • SVD
    • Statistics Math
      • 程序员的数学基础课
      • 数学基础
      • 统计&高数
      • 统计题目
      • 线性代数
      • 组合数学
      • Discrete Choice Model
      • Nested Choice Model
  • Course Note
    • 基于TensorFlow的机器学习速成课程
      • [Key ML Terminology](CourseNote/基于TensorFlow的机器学习速成课程/Key ML Terminology.md)
    • 集训营
      • 任务说明
      • 算法实践1.1模型构建
      • 算法实践1.2模型构建之集成模型
      • 算法实践2.1数据预处理
    • 李宏毅机器学习
      • 10DNN训练Tips
        • Chapter 18
      • 16无监督学习
        • Chapter 25
    • 贪心NLP
      • 贪心NLP笔记
    • Cs 224 N 2019
      • [A Simple But Tough To Beat Baseline For Sentence Embeddings](CourseNote/cs224n2019/A Simple but Tough-to-beat Baseline for Sentence Embeddings.md)
      • [Lecture 01 Introduction And Word Vectors](CourseNote/cs224n2019/Lecture 01 Introduction and Word Vectors.md)
      • [Lecture 02 Word Vectors 2 And Word Senses](CourseNote/cs224n2019/Lecture 02 Word Vectors 2 and Word Senses.md)
      • [Lecture 03 Word Window Classification Neural Networks And Matrix Calculus](CourseNote/cs224n2019/Lecture 03 Word Window Classification, Neural Networks, and Matrix Calculus.md)
      • [Lecture 04 Backpropagation And Computation Graphs](CourseNote/cs224n2019/Lecture 04 Backpropagation and Computation Graphs.md)
      • [Lecture 05 Linguistic Structure Dependency Parsing](CourseNote/cs224n2019/Lecture 05 Linguistic Structure Dependency Parsing.md)
      • [Lecture 06 The Probability Of A Sentence Recurrent Neural Networks And Language Models](CourseNote/cs224n2019/Lecture 06 The probability of a sentence Recurrent Neural Networks and Language Models.md)
      • Stanford NLP
    • Deep Learning Book Goodfellow
      • Books
        • Deep Learning Book Chapter Summaries Master
      • 提纲
      • C 5
      • C 6
      • [Part I Applied Math And Machine Learning Basics](CourseNote/Deep-Learning-Book-Goodfellow/Part I - Applied Math and Machine Learning basics.md)
    • Lihang
    • NLP实战高手课
      • 极客时间_NLP实战高手课
    • 工具&资料
    • 机器学习、深度学习面试知识点汇总
    • 七月kaggle课程
    • 算法工程师
    • 贪心科技机器学习必修知识点特训营
    • 唐宇迪机器学习
    • 语言及工具
    • AI技术内参
    • Suggestions
  • Data Related
    • 数据质量
      • 置信学习
    • 自然语言处理中的数据增广_车万翔
      • 自然语言处理中的数据增广
    • Mixup
    • 数据不均衡问题
    • 数据增强的方法
  • Knowledge Graph
    • Information Extraction
      • 联合抽取
        • PRGC
      • Code
        • BERT微调
      • NER
        • 阅读理解做NER
          • MRC
        • FLAT
        • Global Pointer
        • 命名实体识别NER
    • Keyword Extraction
      • 关键词抽取
    • 小米在知识表示学习的探索与实践
    • KG
  • Multi Task
    • EXT 5
      • Ex T 5
  • NLG
    • Dailogue
      • 比赛
        • 对话评估比赛
          • [simpread-DSTC10 开放领域对话评估比赛冠军方法总结](NLG/Dailogue/比赛/对话评估比赛/simpread-DSTC10 开放领域对话评估比赛冠军方法总结.md)
      • 任务型对话
        • DST
          • DST概述
        • NLG
          • NLG概述
        • NLU
          • NLU概述
        • 任务型对话概述
        • simpread-任务型对话系统预训练最新研究进展
      • 问答型对话
        • 检索式问答
          • 基于预训练模型的检索式对话系统
          • 检索式文本问答
        • 业界分享
          • 低资源场景下的知识图谱表示学习和问答_阿里_李杨
          • QQ浏览器搜索智能问答
        • 问答型对话系统概述
      • 闲聊型对话
        • 闲聊型对话系统概述
      • 业界分享
        • 人工智能与心理咨询
        • 腾讯多轮对话机器人
        • 微软小冰
        • 小布助手闲聊生成式算法
        • 美团智能客服实践_江会星
        • 去哪儿智能客服探索和实践
        • 实时语音对话场景下的算法实践_阿里_陈克寒
        • 智能语音交互中的无效query识别_小米_崔世起
        • UNIT智能对话
      • 主动对话
      • EVA
        • EVA分享
        • EVA模型
      • PLATO
      • RASA
    • Machine Translation
      • 业界分享
        • 爱奇艺台词翻译分享
      • Paper
        • Deep Encoder Shallow Decoder
    • RAGRelated
    • Text 2 SQL
      • M SQL
        • [M SQL 2](NLG/Text2SQL/M-SQL/M-SQL (2).md)
      • [Text2SQL Baseline解析](NLG/Text2SQL/Text2SQL Baseline解析.md)
      • Text 2 SQL
    • Text Summarization
      • [文本摘要][paper]CTRLSUM
      • 文本摘要
  • Pre Training
    • 业界分享
      • 超大语言模型与语言理解_黄民烈
        • 超大语言模型与语言理解
      • 大模型的加速算法_腾讯微信
        • 大模型的加速算法
      • 孟子轻量化预训练模型
      • 悟道文汇文图生成模型
      • 悟道文澜图文多模态大模型
      • 语义驱动可视化内容创造_微软
        • 语义驱动可视化内容创造
    • Base
      • Attention
      • Mask
        • NLP中的Mask
      • Position Encoding
        • 位置编码
    • BERT
      • ALBERT
      • Bert
        • Venv
          • Lib
            • Site Packages
              • idna-3.2.dist-info
                • LICENSE
              • Markdown-3.3.4.dist-info
                • LICENSE
              • Tensorflow
                • Include
                  • External
                    • Libjpeg Turbo
                      • LICENSE
                  • Unsupported
                    • Eigen
                      • CXX 11
                        • Src
                          • Tensor
              • Werkzeug
                • Debug
                  • Shared
                    • ICON LICENSE
        • CONTRIBUTING
        • Multilingual
      • Ro BER Ta
      • BERT
      • BERT面试问答
      • BERT源码解析
      • NSP BERT
    • BERT Flow
    • BERT Zip
      • Distilling The Knowledge In A Neural Network
      • TINYBERT
      • 模型压缩
    • CPM
    • CPT
      • 兼顾理解和生成的中文预训练模型CPT
    • ELECTRA
    • EL Mo
    • ERNIE系列语言模型
    • GPT
    • MBART
    • NEZHA
    • NLG Sum
      • [simpread-预训练时代下的文本生成|模型 & 技巧](Pre-training/NLGSum/simpread-预训练时代下的文本生成|模型 & 技巧.md)
    • Prompt
      • 预训练模型的提示学习方法_刘知远
        • 预训练模型的提示学习方法
    • T 5
      • Unified SKG
      • T 5
    • Transformer
    • Uni LM
    • XL Net
    • 预训练语言模型
    • BERT变种
  • Recsys
    • 多任务Multi-task&推荐
    • 推荐介绍
    • 推荐系统之召回与精排
      • 代码
        • Python
          • Recall
            • Deep Match Master
              • Docs
                • Source
                  • Examples
                  • FAQ
                  • Features
                  • History
                  • Model Methods
                  • Quick Start
    • 业界分享
      • 腾讯基于知识图谱长视频推荐
    • 召回
    • Sparrow Rec Sys
    • 深度学习推荐系统实战
    • 推荐模型
    • Deep FM
  • Search
    • 搜索
    • 业界分享
      • 爱奇艺搜索排序算法实践
      • 语义搜索技术和应用
    • 查询关键字理解
    • 搜索排序
    • BM 25
    • KDD21-淘宝搜索中语义向量检索技术
    • query理解
    • TFIDF
  • Self Supervised Learning
    • Contrastive Learning
      • 业界分享
        • 对比学习在微博内容表示的应用_张俊林
      • Paper
      • R Drop
      • Sim CSE
    • 自监督学习
  • Text Classification
    • [多标签分类(Multi-label Classification)](TextClassification/多标签分类(Multi-label Classification)/多标签分类(Multi-label Classification).md)
    • Fast Text
    • Text CNN
    • 文本分类
  • Text Matching
    • 文本匹配和多轮检索
    • CNN SIM
    • Word Embedding
      • Skip Gram
      • Glove
      • Word 2 Vec
    • 文本匹配概述
  • Tool
    • 埋点
    • 向量检索(Faiss等)
    • Bigdata
      • 大数据基础task1_创建虚拟机+熟悉linux
      • 任务链接
      • Mr
      • Task1参考答案
      • Task2参考答案
      • Task3参考答案
      • Task4参考答案
      • Task5参考答案
    • Docker
    • Elasticsearch
    • Keras
    • Numpy
    • Python
      • 可视化
        • Interactivegraphics
        • Matplotlib
        • Tkinter
        • Turtle
      • 数据类型
        • Datatype
      • python爬虫
        • Python Scraping Master
          • phantomjs-2.1.1-windows
        • Regularexp
        • Scrapying
        • Selenium
      • 代码优化
      • 一行代码
      • 用python进行语言检测
      • Debug
      • Exception
      • [Features Tricks](Tool/python/Features & Tricks.md)
      • Fileprocess
      • Format
      • Functional Programming
      • I Python
      • Magic
      • Math
      • Os
      • Others
      • Pandas
      • Python Datastructure
      • Python操作数据库
      • Streamlit
      • Time
    • Pytorch
      • Dive Into DL Py Torch
        • 02 Softmax And Classification
        • 03 Mlp
        • 04 Underfit Overfit
        • 05 Gradient Vanishing Exploding
        • 06 Text Preprocess
        • 07 Language Model
        • 08 Rnn Basics
        • 09 Machine Translation
        • 10 Attention Seq 2 Seq
        • 11 Transformer
        • 12 Cnn
        • 14 Batchnorm Resnet
        • 15 Convexoptim
        • 16 Gradientdescent
        • 17 Optim Advance
    • Spark
      • Pyspark
        • pyspark之填充缺失的时间数据
      • Spark
    • SQL
      • 数据库
      • Hive Sql
      • MySQL实战45讲
    • Tensor Flow
      • TensorFlow入门
  • Common
  • NLP知识体系
Powered by GitBook
On this page
  • graphics库
  • 交互式图形用户接口
  • GraphWin对象
  • Tkinter库

Was this helpful?

  1. Tool
  2. Python
  3. 可视化

Interactivegraphics

Graphical User Interface, GUI Tkinter-Python标准GUI Graphics-基于Tkinter扩展 Turtle-python内置的图形库

graphics库

原点在左上角,x轴从坐到右是递增,y轴从上到下是递增

from graphics import *
circ = Circle(Point(100, 100), 30)
# 在(100,100)坐标处建立圆
win = GraphWin()
circ.draw(win)

两个不同的变量可能表示同一个对象

编写卡通脸的程序,两个眼睛间隔40像素长度

win = GraphWin()
leftEye = Circle(Point(80, 80), 5)
leftEye.setFill("yellow")
leftEye.setOutline("red")
rightEye = leftEye
rightEye.move(40, 0)
leftEye.draw(win)
rightEye.draw(win)

解决方法 为左右眼分别创建两个不同的圆对象

from graphics import *
win = GraphWin()
face = Circle(Point(100, 95), 50)
leftEye = Circle(Point(80, 80), 5)
leftEye.setFill("yellow")
leftEye.setOutline("red")
rightEye = Circle(Point(120, 80), 5)
rightEye.setFill("yellow")
rightEye.setOutline("red")
mouth = Line(Point(80, 110), Point(120, 110))
face.draw(win)
mouth.draw(win)
leftEye.draw(win)
rightEye.draw(win)

交互式图形用户接口

连续点击10次鼠标,返回其坐标值

from graphics import *
def main():
    win = GraphWin("Click Me!")
    for i in range(10):
        p = win.getMouse()
        print("You clicked at:", p.getX(), p.getY())
if __name__ == '__main__':
    main()

在窗口中点击5个点来画一个五边形

from graphics import *
win = GraphWin("Draw a polygon",300,300)
win.setCoords(0.0, 0.0, 300.0, 300.0)
message = Text(Point(150, 20), "Click on five points")
message.draw(win)
#获得多边形的5个点
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
p4 = win.getMouse()
p4.draw(win)
p5 = win.getMouse()
p5.draw(win)
# 使用Polygon对象绘制多边形
polygon = Polygon(p1, p2, p3, p4, p5)
polygon.setFill("peachpuff")
polygon.setOutline("black")
polygon.draw(win)
# 等待响应鼠标事件,退出程序
message.setText("Click anywhere to quit.")
win.getMouse()

Text对象:setText()和getText() Entry对象:setText()和getText() 内容可以被用户修改

from graphics import *
def main():
    win = GraphWin("Click Me!")
    for i in range(10):
        p = win.getMouse()
        print("You clicked at:", p.getX(), p.getY())
if __name__ == '__main__':
    main()

在窗口中点击5个点来画一个五边形

from graphics import *
win = GraphWin("Celsius Temperature",400,300)
win.setCoords(0.0, 0.0, 3.0, 4.0)
# 绘制接口
Text(Point(1,3), " Celsius Temperature:").draw(win)
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
input = Entry(Point(2,3), 5)
input.setText("0.0")
input.draw(win)
output = Text(Point(2,1), "")
output.draw(win)
button = Text(Point(1.5,2.0), "Convert It")
button.draw(win)
Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)
# 等待鼠标点击
win.getMouse()
# 转换输入
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32.0
# 显示输出,改变按钮
output.setText(fahrenheit)
button.setText("Quit")
# 等待响应鼠标点击,退出程序
win.getMouse()
win.close()

GraphWin对象

一个程序可以定义任意数量的窗体 GraphWin() 默认标题是"Graphics Window" 默认大小为200*200

GraphWin对象常用方法

  • plot(x, y, color) 在窗口中(x,y)位置绘制像素。颜色参数可选,默认值为黑色。

  • plotPixel(x, y, Color) 在“原始”位置(x,y)处绘制像素,忽略* setCoords()方法设置的坐标变换。

  • setBackground(color) 将窗口背景颜色设为指定颜色,默认值为灰色。

  • close() 关闭屏幕上的窗口。

  • getMouse() 程序等待用户在窗口内点击鼠标,返回值为点击处的位置,并以Point对象返回。

  • setCoords(xll, yll, xur, yur) 设置窗口的坐标系。左下角是(xll,yll),右上角是(xur,yur)。所有后面的绘制都以这个坐标系做参照(plotPexil除外)

  • 图形对象:点、线段、圆、椭圆、矩形、多边形以及文本

  • 默认初始化:黑色边框;没有被填充;

图形对象通用方法

  • setFill(color) 设置对象内部填充颜色。

  • setOutline(color) 设置对象边框颜色。

  • setWidth(pixels) 设置对象的宽度(对Point类不起作用)。

  • draw(aGraphWin) 在指定的窗口中绘制对象。

  • undraw() 从窗口中删除该对象。如该对象没有在窗口中画出将会报错。

  • move(dx,dy) 将对象沿x轴和y轴分别移动dx和dy单位长度。

  • clone()返回该对象的副本。

Point对象方法

  • Point(x,y) 以指定坐标的值(x, y)构造一点

  • getX() 返回该点的x坐标值

  • getY() 返回该点的y坐标值

Line对象方法

  • Line(point1, point2) 构造一个从点point1到点point2的线段

  • setArrow(string) 设置线段的箭头样式。箭头可以绘制在左端,右端,或者两端都有。string参数值为’first’, ’last’, ’both’,或 ’none’,默认值为’none’。

  • getCenter() 返回线段中点的坐标值。

  • getP1(), getP2() 返回线段相应端点的坐标值。

Circle对象方法

  • Circle(centerPoint, radius) 根据给定圆心和半径构建圆

  • getCenter() 返回圆心的值

  • getRadius() 返回圆的半径长度

  • getP1(), getP2() 返回值为该圆边框对应点,对应点指的是该圆外接正方形的对角点。

Rectangle对象方法

  • Rectangle(point1, point2) 以point1和point2为对角点创建一个矩形。

  • getCenter() 返回矩形的中心点的克隆值。

  • getP1(), getP2() 返回构造矩形的对角点的克隆值

Oval对象方法

  • Oval(point1, point2) 在点point1和point2指定的边界框中创建一个椭圆。

  • getCenter() 返回椭圆的中心点的坐标值

  • getP1(), getP2() 返回构造椭圆的对角点的坐标值

Polygon 对象方法

  • Polygon (point1, point2, point3, ...) 根据给定的顶点构造一个多边形。也可以只用一个顶点列表作为参数

  • getPoints() 返回构造多边形的顶点值的列表

Text 对象方法

  • Text(anchorPoint, string) 以anchorPoint点的位置为中心,构建了一个内容为string的文本对象。

  • setText(string) 设置文本对象的内容

  • getText() 返回当前文本内容。

  • getAnchor() 返回文本显示中间位置点anchor的坐标值。

  • setFace(family) 设置文本字体。family可选值为:’helvetica’,’courier’, ’times roman’, 以及 ’arial’.

  • setSize(point) 设置字体大小为给定点point的大小。合法数值为5-36。

  • setStyle(style) 设置字体的风格。可选值为’normal’, ’bold’, ’italic’,以及 ’bold italic’。

  • setTextColor(color) 设置文本颜色。与setFill效果相同。

图形颜色

  • Python中颜色由字符串指定

  • 很多颜色具有不同深浅

    • 红色逐渐加深

    • ‘red1’‘red2’‘red3’ ‘red4’

color_rgb(red,green,blue)函数

  • 设定颜色数值获得颜色

  • 三个参数为0-255范围内的整数

  • 返回一个字符串

    • color_rgb(255,0,0) 亮红色,

    • color_rgb(130,0,130) 中度洋红色。

温度转换程度示例

from graphics import *
 
win = GraphWin("Celsius Converter", 400, 300)
win.setCoords(0.0, 0.0, 3.0, 4.0)
# 绘制接口
Text(Point(1,3), " Celsius Temperature:").draw(win)
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
input = Entry(Point(2,3), 5)
input.setText("0.0")
input.draw(win)
output = Text(Point(2,1),"")
output.draw(win)
button = Text(Point(1.5,2.0),"Convert It")
button.draw(win)
Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)
# 等待鼠标点击
win.getMouse()
# 转换输入
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32.0
# 显示输出,改变按钮
output.setText(fahrenheit)
button.setText("Quit")
# 等待响应鼠标点击,退出程序
win.getMouse()
win.close()

计算温度值设定窗口颜色: 温度越高,颜色越偏红 温度越低,颜色越偏蓝 setBackground(Newcolor)设置窗口背景颜色。 假定输入温度范围为0-100, 颜色权重weight=输入温度/100 newcolor的rgb计算: 红色分量=255weight 绿色分量=66+150(1-weight) 蓝色分量=255(1-weight)

from graphics import *
 
def convert(input):
    celsius = eval(input.getText())    # 输入转换
    fahrenheit = 9.0/5.0 * celsius + 32
    return fahrenheit 
def colorChange(win,input):
    cnum = eval(input.getText())
    weight = cnum / 100.0
    newcolor =color_rgb(255*weight,66+150*(1-weight),255*(1-weight))
    win.setBackground(newcolor)
def main():
    win = GraphWin("Celsius Converter", 400, 300)
    win.setCoords(0.0, 0.0, 3.0, 4.0)
    # 绘制输入接口
    Text(Point(1,3),
         " Celsius Temperature:").draw(win)
    Text(Point(2,2.7),
         " (Please input 0.0-100.0 )").draw(win)
    Text(Point(1,1),
         "Fahrenheit Temperature:").draw(win)
    input = Entry(Point(2,3), 5)
    input.setText("0.0")
    input.draw(win)
    output = Text(Point(2,1),"")
    output.draw(win)
    button = Text(Point(1.5,2.0),"Convert It")
    button.draw(win)
    rect = Rectangle(Point(1,1.5), Point(2,2.5))
    rect.draw(win)
    # 等待鼠标点击
    win.getMouse()
    result = convert(input)    # 转换输入
    output.setText(result)    # 显示输出 
    # 改变颜色
    colorChange(win,input)
    # 改变按钮字体
    button.setText("Quit")
    # 等待点击事件,退出程序
    win.getMouse()
    win.close()
 
if __name__ == '__main__':
    main()

Tkinter库

创建GUI程序的基本步骤为: 导入Tk模块. 创建GUI应用程序的主窗口. 添加控件或GUI应用程序. 进入主事件循环,等待响应用户触发事件.

15中常见的Tk控件 Button, Canvas, Checkbutton, Entry, Frame, Label, Listbox, Menubutton, Menu, Message, Radiobutton, Scale Scrollbar, Text, Toplevel, Spinbox PanedWindow, LabelFrame, tkMessageBox

共同属性

  • Dimensions :尺寸

  • Colors:颜色

  • Fonts:字体

  • Anchors:锚

  • Relief styles:浮雕式

  • Bitmaps:显示位图

  • Cursors:光标的外形 特有属性

界面布局 Tkinter三种几何管理方法 pack() grid() place() 简单GUI示例

from tkinter import *
tk = Tk()
label = Label(tk, text="Welcome to Python Tkinter")
button = Button(tk, text="Click Me")
label.pack()
button.pack()
tk.mainloop()

响应用户事件示例

from tkinter import *
def processOK():
    print("OK button is clicked")
def processCancel():
    print("Cancel button is clicked")
def main():
    tk = Tk()
    btnOK = Button(tk, text="OK", fg = "red", command = processOK)
    btnCancel = Button(tk, text = "Cancel", bg = "yellow", command = processCancel)
    btnOK.pack()
    btnCancel.pack()
    tk.mainloop()

显示文字、图片、绘制图形

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width = 200, height = 200)
canvas.pack()
canvas.create_text(100, 40, text = "Welcome to Tkinter", fill = "blue", font = ("Times", 16))
myImage = PhotoImage(file = "python_logo.gif")
canvas.create_image(10, 70, anchor = NW, image = myImage)
canvas.create_rectangle(10, 70, 190, 130)
tk.mainloop()

控制图形移动的示例

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width = 400, height = 400)
canvas.pack()
def moverectangle(event):
    if event.keysym == "Up":
        canvas.move(1, 0, -5)
    elif event.keysym == "Down":
        canvas.move(1, 0, 5)
    elif event.keysym == "Left":
        canvas.move(1, -5, 0)
    elif event.keysym == "Right":
        canvas.move(1, 5, 0)
canvas.create_rectangle(10,10,50,50,fill="red")
canvas.bind_all("<KeyPress-Up>",moverectangle)
canvas.bind_all("<KeyPress-Down>",moverectangle)
canvas.bind_all("<KeyPress-Left>",moverectangle)
canvas.bind_all("<KeyPress-Right>",moverectangle)

基于tkinter库完成聊天窗口GUI 见ChatWin.py

Previous可视化NextMatplotlib

Last updated 2 years ago

Was this helpful?