方式1 tkiner自带的打开图片的方式,只能打开gif图片
import tkinter as tk
window = tk.Tk()
window.title('test')#设置窗口名
window.geometry('200x200')#设置窗口大小
canvas = tk.Canvas(window,height=400,width=500)
image_file = tk.PhotoImage(file = r'D:\xs.gif')
image = canvas.create_image(100,100,anchor='center',image=image_file)
canvas.pack()
window.mainloop()
如图
方式2 用PIL,可打开jpg,png,gif 类型的图片,其他的不知道可不可以,没有用到过~~~
import tkinter as tk
from PIL import Image,ImageTk
window = tk.Tk()
window.title('test')#设置窗口名
window.geometry('300x200')#设置窗口大小
canvas = tk.Canvas(window,height=400,width=500)
img = Image.open(r'D:\u0.jpg')
image_file = ImageTk.PhotoImage(img) #注:如果显示图片这个功能定义在一个方法里,image_file 一定要申明为全局变量,窗口才会显示图片
image = canvas.create_image(100,50,anchor='center',image=image_file)
canvas.pack()
window.mainloop()
from tkinter import *
from PIL import Image,ImageTk
class CW:
def __init__(self):
self.window = Tk()
self.window.title('test')#设置窗口名
self.window.geometry('200x200')#设置窗口大小
self.frame = Frame(self.window)
self.frame.pack()
self.canvas = Canvas(self.frame,height=400,width=500)
self.scoller()
self.show()
def show(self):
global image_file
img = Image.open(r'D:\u0.jpg')
image_file = ImageTk.PhotoImage(img)
self.canvas.create_image(0,0,anchor='center',image=image_file)
self.canvas.pack()
def scoller(self):
yscor = Scrollbar(self.frame, orient=VERTICAL, cursor='draft_small') #垂直方向滚动条
yscor.pack(side='right', fill=Y)
yscor.config(command=self.canvas.yview)
xscor = Scrollbar(self.frame, orient=HORIZONTAL, cursor='draft_small')#水平方向滚动条
xscor.pack(side='bottom', fill=X)
xscor.config(command=self.canvas.xview)
self.canvas.config(yscrollcommand=yscor.set,xscrollcommand=xscor.set) # 增加这句滚动条才有滚动
self.frame.bind("" ,self.onFrameConfigure) # 增加了这句后滚动条功能才正常
def onFrameConfigure(self,event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def __call__(self):
self.window.mainloop()
if __name__ == '__main__':
CW()()