如何使用画布显示窗口获取Tkinter小部件的大小?

时间:2019-02-07 20:39:12

标签: python tkinter tkinter-canvas ttk tkinter-layout

import tkinter as tk
import tkinter.ttk as ttk

root=tk.Tk()

canvas = tk.Canvas(root, width=300, height=300, borderwidth=0, highlightthickness=0, bg="#000040")
canvas.pack(fill=tk.BOTH, expand=True)

notebookwidth=215

bgcolor="#ECE9D8"

tabs1=ttk.Notebook(root)

tree=ttk.Treeview( tabs1, columns=('Name', 'Info'))

tree.column('#0', stretch=tk.YES)
tree.column('#1', stretch=tk.YES)
tree.column('#2', stretch=tk.YES)

# Initialize the counter
i = 0
s=["Name","Venus","Body Type","Terrestrial Planet","Diameter","12104 km","Orb Distance","108m km","Gravity","0.91"]

for x in range(0, len(s), 2):
    tree.insert('', 'end', text="Item_"+str(i), values=(s[x], s[x+1]))
    # Increment counter
    i = i + 1 

#tree.pack(side=tk.LEFT, anchor=tk.NW, fill=tk.BOTH, expand=True)
tree.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)   
tabs1.add(frame, text="Body Info")
display_window=canvas.create_window(10, 10, anchor=tk.NW, window=tabs1, width=notebookwidth)

root.mainloop()

Linux〜python 3.5

我意识到,因为我知道画布上显示窗口的大小,所以我可以更改列的宽度

tree.column('#0', stretch=tk.YES, minwidth=0, width=0)
tree.column('#1', stretch=tk.YES, width= 110)
tree.column('#2', stretch=tk.YES, width=110)

如果有一种LayoutManager方式可以拉伸它,我会更喜欢,因为我也想隐藏标题和idd列。我也觉得这可以帮助我更好地了解LayoutManager。

还检查了许多有关使用窗口小部件尺寸的文章,其中大多数是关于以编程方式调整窗口大小的,这是启动时遇到的问题

我尝试使用不同的父母,背包,格子。我不明白如何将displaywindow用作父项,它会在tk中抛出python错误。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

不确定我是否完全了解您的要求,但是在所附的代码中,matplotlib图形遵循画布的大小,直到达到使用滚动条所使用的特定大小(仅在高度上)为止。我在stackoverflow上找到的大多数代码。 /丹尼尔

import math
import sys
if sys.version_info[0] < 3:
  from Tkinter import Tk, Button, Frame, Canvas, Scrollbar
  import Tkconstants
else:
  from tkinter import Tk, Button, Frame, Canvas, Scrollbar
  import tkinter.constants as Tkconstants

from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pprint

frame = None
canvas = None


def FrameHeight(event):
    canvas_height = event.height
    canvas_width = event.width
    print(canvas_height)
    # canvas.itemconfig(cwid, height=canvas_height)
    canvas.itemconfig(cwid, width=canvas_width)
    print(frame.winfo_height())
    print('FIGINFO')
    print(figure.get_size_inches())
    print(figure.dpi)
    size = figure.get_size_inches() * figure.dpi  # size in pixels
    print(size)
    if size[1] < frame.winfo_height():
        canvas.itemconfig(cwid, height=canvas_height)
    if size[1] > 500:
        canvas.itemconfig(cwid, height=canvas_height)

    # wi, hi = [i * figure.dpi for i in figure.get_size_inches()]


def printBboxes(label=""):
  global canvas, mplCanvas, interior, interior_id, cwid
  print("  "+label,
    "canvas.bbox:", canvas.bbox(Tkconstants.ALL),
    "mplCanvas.bbox:", mplCanvas.bbox(Tkconstants.ALL))

def addScrollingFigure(figure, frame):
  global canvas, mplCanvas, interior, interior_id, cwid
  # set up a canvas with scrollbars
  canvas = Canvas(frame)
  canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)

  # xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
  yScrollbar = Scrollbar(frame)

  # xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)
  yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)

  # canvas.config(xscrollcommand=xScrollbar.set)
  # xScrollbar.config(command=canvas.xview)
  canvas.config(yscrollcommand=yScrollbar.set)
  yScrollbar.config(command=canvas.yview)

  # plug in the figure
  figAgg = FigureCanvasTkAgg(figure, canvas)
  mplCanvas = figAgg.get_tk_widget()
  #mplCanvas.grid(sticky=Tkconstants.NSEW)

  # and connect figure with scrolling region
  cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)
  printBboxes("Init")
  canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
  canvas.bind('<Configure>', FrameHeight)

def changeSize(figure, factor):
  global canvas, mplCanvas, interior, interior_id, frame, cwid
  oldSize = figure.get_size_inches()
  print("old size is", oldSize)
  figure.set_size_inches([factor * s for s in oldSize])
  wi,hi = [i*figure.dpi for i in figure.get_size_inches()]
  print("new size is", figure.get_size_inches())
  print("new size pixels: ", wi,hi)
  mplCanvas.config(height=hi) ; printBboxes("A")
  #mplCanvas.grid(sticky=Tkconstants.NSEW)
  canvas.itemconfigure(cwid, height=hi) ; printBboxes("B")
  canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
  figure.canvas.draw() ; printBboxes("C")
  print()

if __name__ == "__main__":
  root = Tk()
  root.rowconfigure(1, weight=1)
  root.columnconfigure(1, weight=1)

  frame = Frame(root)
  frame.grid(column=1, row=1, sticky=Tkconstants.NSEW)
  frame.rowconfigure(1, weight=1)
  frame.columnconfigure(1, weight=1)

  figure = plt.figure(dpi=100, figsize=(4, 5))
  a = figure.add_subplot(311)
  b = figure.add_subplot(312)
  c = figure.add_subplot(313)
  a.plot(range(10), [math.sin(x) for x in range(10)])
  b.plot(range(10), [math.sin(x) for x in range(10)])
  c.plot(range(10), [math.sin(x) for x in range(10)])

  addScrollingFigure(figure, frame)

  buttonFrame = Frame(root)
  buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)
  biggerButton = Button(buttonFrame, text="larger",
                        command=lambda : changeSize(figure, 1.5))
  biggerButton.grid(column=1, row=1)
  smallerButton = Button(buttonFrame, text="smaller",
                         command=lambda : changeSize(figure, .5))
  smallerButton.grid(column=1, row=2)

  root.mainloop()

"""
  interior = Frame(canvas) #Frame(mplCanvas) #cannot
  interior_id = canvas.create_window(0, 0, window=interior)#, anchor=Tkconstants.NW)
  canvas.config(scrollregion=canvas.bbox("all"),width=200,height=200)
  canvas.itemconfigure(interior_id, width=canvas.winfo_width())

  interior_id = canvas.create_window(0, 0, window=interior)#, anchor=Tkconstants.NW)
  canvas.config(scrollregion=canvas.bbox("all"),width=200,height=200)
  canvas.itemconfigure(interior_id, width=canvas.winfo_width())
"""