python3 tkinter实现添加图片和文本

yipeiwu_com6年前Python基础

本文在前面文章基础上介绍tkinter添加图片和文本,在这之前,我们需要安装一个图片库,叫Pillow,这个需要下载exe文件,根据下面图片下载和安装。

下载完后直接双击安装exe,默认点击下一步,直到安装完成,会自动安装到Python3.6下的\lib\site-packages\PIL

# tkinter实现菜单功能
from tkinter import *
from PIL import Image, ImageTk
 
class Window(Frame):
 
  def __init__(self, master= None):
 
    Frame.__init__(self, master)
    self.master = master
    self.init_window()
 
  def init_window(self):
 
    self.master.title("第一个窗体")
 
    self.pack(fill=BOTH, expand=1)
 
    # 实例化一个Menu对象,这个在主窗体添加一个菜单
    menu = Menu(self.master)
    self.master.config(menu=menu)
 
    # 创建File菜单,下面有Save和Exit两个子菜单
    file = Menu(menu)
    file.add_command(label='Save')
    file.add_command(label='Exit', command=self.client_exit)
    menu.add_cascade(label='File',menu=file)
 
    # 创建Edit菜单,下面有一个Undo菜单
    edit = Menu(menu)
    edit.add_command(label='Undo')
    edit.add_command(label='Show Image',command=self.showImg)
    edit.add_command(label='Show Text',command=self.showTxt)
    menu.add_cascade(label='Edit',menu=edit)
    
 
  def client_exit(self):
    exit()
 
  def showImg(self):
    load = Image.open('pic.jpg') # 我图片放桌面上
    render= ImageTk.PhotoImage(load)
 
    img = Label(self,image=render)
    img.image = render
    img.place(x=0,y=0)
 
  def showTxt(self):
    text = Label(self, text='GUI图形编程')
    text.pack()
 
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()

运行,点击Edit菜单下的Show Image,会显示一张图片,点击Show Text会出现一行文本。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用PDB简单调试Python程序简明指南

使用PDB简单调试Python程序简明指南

在 Python 中也可以像 gcc/gdb 那样调试程序,只要在运行 Python 程序时引入 pdb 模块(假设要调试的程序名为 d.py): 复制代码 代码如下: $ vi d.p...

python使用tomorrow实现多线程的例子

python使用tomorrow实现多线程的例子

如下所示: import time,requestes from tomorrow import threads @threads(10)#使用装饰器,这个函数异步执行 def d...

python实现顺序表的简单代码

python实现顺序表的简单代码

 顺序表即线性表的顺序存储结构。它是通过一组地址连续的存储单元对线性表中的数据进行存储的,相邻的两个元素在物理位置上也是相邻的。比如,第1个元素是存储在线性表的起始位置LOC(...

利用Python实现原创工具的Logo与Help

利用Python实现原创工具的Logo与Help

前言 当我们使用Python完成自己的原创的工具时,比如:端口扫描、弱口令爆破等。你是否想过添加自己的Logo,以及简要的帮助信息? 如下: Sqlmap的Logo Nmap的说...

python daemon守护进程实现

python daemon守护进程实现

假如写一段服务端程序,如果ctrl+c退出或者关闭终端,那么服务端程序就会退出,于是就想着让这个程序成为守护进程,像httpd一样,一直在后端运行,不会受终端影响。 守护进程英文为dae...