我试图用Python的tkinter模块和Canvas编写一个小的画图软件,当我在画布中打开一个图片时,发现图片的尺寸大于了我的画布尺寸,未能显示完全。
因此我给画布添加了滚动条:
结果发现,依然存在图片显示不完全的问题,而且滚动条是灰色的,根本无法滚动,明明跟画布绑定在一起了的。
以下是代码:
from tkinter import *
from tkinter import filedialog
from PIL import Image,ImageTk
def open_image():
global img
global painting
while 1:
try:
img=Image.open(filedialog.askopenfilename(filetypes=[('PNG','png'), ('JPG','jpg'), ('GIF','gif')]))#,initiadir='D:/Python3/pythonc/python作品/程序设计参赛项目-唐铭鑫/paintings'))
painting=ImageTk.PhotoImage(img)
canvas.create_image(0,0,anchor=NW,image=painting)
canvas.update()
break
except AttributeError:
choice=messagebox.askretrycancel('图片打开错误','图片打开错误,是否重新选择图片')
if choice==True:
continue
else:
break
root=Tk()
paint_area=Frame(root,height=590,width=1140,bg='lightgrey',relief=GROOVE,borderwidth=8)
paint_area.pack()
paint_area_=Frame(paint_area,height=510,width=1080)
paint_area_.place(x=10,y=15)
canvas=Canvas(paint_area_,height=510,width=1080)
canvas_x_scrollbar=Scrollbar(paint_area_,orient=HORIZONTAL)
canvas_x_scrollbar.pack(side=BOTTOM,fill=X)
canvas_y_scrollbar=Scrollbar(paint_area_,orient=VERTICAL)
canvas_y_scrollbar.pack(side=RIGHT,fill=Y)
canvas.pack(side=LEFT,fill=BOTH,expand=True)
canvas_x_scrollbar.config(command=canvas.xview)
canvas_y_scrollbar.config(command=canvas.yview)
canvas.config(yscrollcommand=canvas_y_scrollbar.set,xscrollcommand=canvas_x_scrollbar.set,scrollregion=(0,0,200,200))
open_button=Button(root,text=' ==>打开图片<==',bg='gainsboro',relief='groove',width=14,padx=2,command=lambda:open_image())
open_button.pack()
root.mainloop()
有谁能告诉我这是为什么吗?