创建将图像放置在画布上的程序。我想在画布上添加一个X轴和Y轴滚动条,但我不知道如何。
我通常会使用Frame,但我正在使用的程序是使用tkinter.Toplevel而不是使用Frame。
#----- Imports ---------------------
import os
import os.path
import sys
import tkinter
tk = tkinter
from tkinter import font
#----- Set flag for JPEG support ---
noJPEG = False
try:
from PIL import Image
Pimg = Image
from PIL import ImageDraw
Pdraw = ImageDraw.Draw
from PIL import ImageTk
Pimgtk = ImageTk
except ImportError:
noJPEG = True
#
#------------------------------------
# Create an invisible global parent window to hold all children.
# Facilitates easy closing of all windows by a mouse click.
_root = tk.Tk()
_root.withdraw()
#
#------------------------------------
# A writeable window for holding an image.
#
class ImageView(tk.Canvas):
def __init__(self, image, title=''):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master,
width = 600, height = 500,
scrollregion=(0,0, image.getWidth(),
image.getHeight()))
# Define class fields
## Image properties
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.image = image
self.height = image.getHeight()
self.width = image.getWidth()
# for later
#self.customFont = font.Font(family="Helvetica", size=12)
## Actionable items
self.mouseX = None
self.mouseY = None
self.mouseFxn = None
self.bind("<Button-1>", self.onClick) #bind action to button1 click
self.tags = None
_root.update() #redraw global window
答案 0 :(得分:1)
使用Toplevel
而不是Frame
没有什么特别之处。您可以像对任何容器中的任何可滚动窗口小部件一样附加滚动条。
我从未见过小部件创建它自己的父级。这很不寻常,虽然它确实没有改变任何东西。只需在顶层内添加滚动条即可。
您可能希望切换到grid
而不是pack
,因为这样可以让滚动条正确排列更容易。您只需要移除对self.pack()
的调用,并在代码中添加以下内容:
vsb = tk.Scrollbar(master, orient="vertical", command=self.yview)
hsb = tk.Scrollbar(master, orient="horizontal", command=self.xview)
self.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)