简体   繁体   中英

How to show only a portion of the tkinter canvas by cropping the tkinter window?

I want to be able to zoom into my tkinter canvas. My tkinter canvas is 500x500px, and I only want my window to display the center 200x200px portion of this canvas. How do I do this? I know that I can just specify my window size as 200x200px using root.geometry("200x200+0+0"), but this causes my window to display the top left corner of my canvas, and not the center. Before I do anything, my entire canvas looks like this:

整个画布

Ultimately, I want my window to look like this, with the canvas centered within the window:

期望的最终结果

This is my code:

import tkinter

root = tkinter.Tk()
root.title("")
root.geometry("200x200+0+0")

canvas = tkinter.Canvas(master = root, width = 500, height = 500)

canvas.create_oval(200, 200, 300, 300, outline = "black", fill = "blue")
canvas.pack()

which returns:

我的问题

As you can see, the canvas is not centered, and the window is showing the upper left hand corner at the moment. Does anyone have any suggestions?

Ok, thanks to this stackoverflow post , I found out there is an option when creating a tkinter canvas called scrollregion . The format of the argument is "x0 y0 x1 y1" for anyone that is wondering, where (x0, y0) is the upper-left corner of the area of the canvas I want to show and (x1, y1) is the bottom-right corner of the same area. My code should be fixed to this:

canvas = tkinter.Canvas(master = root, width = 500, height = 500, scrollregion = "150 150 350 350")

Be wary that these coordinates do not account for a scrollbar...I'm still working on figuring that out. Much thanks to this stackoverflow post as well, specifically the following words:

I don't see any difference between putting the y-scrollbar to the bottom or putting the canvas view to the bottom because the two are linked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM