簡體   English   中英

調整 window 的大小時,如何讓我的 Tkinter-Canvas 具有固定的寬度/高度比

[英]How do I let my Tkinter-Canvas have a fixed width/height ratio when resizing the window

我有以下棋盤: 棋盤

而且我希望 canvas 保持棋盤始終保持正方形,無論我如何調整 Window 的大小,任何幫助都將不勝感激!

如果您在 window 中有多個項目並且想要約束單個小部件,這可能會變得復雜。 正確答案將取決於 window 中發生的其他情況以及您定義的調整大小行為。

一個簡單的方法是確保 canvas 位於不會調整大小的區域中。 例如:

import tkinter as tk

root = tk.Tk()

root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)

canvas = tk.Canvas(root, width=400, height=400, bg="bisque")
canvas.grid(row=0, column=1, sticky="nsew")

root.mainloop()

您還可以使用wm_aspect將 window 作為一個整體約束到特定的縱橫比。 這使您可以調整 window 的大小,但 window 作為一個整體將保留特定的縱橫比。

例如,要強制根 window 為正方形,您可以這樣做:

root = tk.Tk()
root.wm_aspect(1, 1, 1, 1)

從 tcl/tk 手冊頁(並翻譯為 python 語法):

window .wm_aspect(?minNumer minDenom maxNumer maxDenom?) - If minNumer , minDenom , maxNumer , and maxDenom are all specified, then they will be passed to the window manager and the window manager should use them to enforce a range of acceptable aspect ratios for window。 window(寬度/長度)的縱橫比將被限制在minNumer/minDenommaxNumer/maxDenom 之間 如果minNumer等都指定為空字符串,則刪除任何現有的縱橫比限制。 如果指定了minNumer等,則該命令返回一個空字符串。 否則,它返回一個包含四個元素的元組,它們是minNumerminDenommaxNumermaxDenom的當前值(如果沒有方面限制生效,則返回一個空字符串)。

您的問題有很多解決方案。 這是一個帶有grid管理器和固定大小的Canvas的。 如果要調整Canvas的大小,則必須使用綁定到<Configure>事件來保持其大小為正方形:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

b = ttk.Button(text='test')
b.grid(column=0, row=0, sticky='ew')
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
canvas = tk.Canvas(root, width=500, height=500, bg="bisque")
canvas.grid(row=0, column=1, rowspan=2, sticky='nw')

root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM