python3 tkinter实现添加图片和文本

yipeiwu_com7年前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设计】。

相关文章

numpy.linalg.eig() 计算矩阵特征向量方式

在PCA中有遇到,在这里记录一下 计算矩阵的特征值个特征向量,下面给出几个示例代码: 在使用前需要单独import一下 >>> from numpy import...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

Python django使用多进程连接mysql错误的解决方法

Python django使用多进程连接mysql错误的解决方法

问题 mysql 查询出现错误 error: (2014, "Commands out of sync; you can't run this command now")1 查询 m...

python进程类subprocess的一些操作方法例子

subprocess.Popen用来创建子进程。 1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。 复制代码 代码如下: def TestPopen(): &nb...

matplotlib给子图添加图例的方法

matplotlib给子图添加图例的方法

代码如下: import matplotlib.pyplot as plt x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2] axe1 = p...