tkinter 画布窗口大小 [英] tkinter Canvas window size

查看:34
本文介绍了tkinter 画布窗口大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道何时调整 Canvas 的大小(例如,当主框架最大化时)新的 Canvas 窗口大小.不幸的是,如果我尝试 self.canvas['width'] ,在我看来,每次我初始化它时都会返回它的宽度,而不是当前的宽度.如何获取当前的 Canvas 窗口尺寸?

I need to know when the Canvas is resized (eg when the master frame gets maximized) the new Canvas window size. Unfortunately, if I try self.canvas['width'] it always seems to me I get back the width it had whenever I initialized it and not the current width. How do I get the current Canvas window dimensions?

推荐答案

当您检索 self.canvas['width'] 时,您是在要求 tkinter 为您提供 configuredem> 小部件的宽度,而不是 实际 宽度.对于实际宽度,您可以使用 .winfo_width().

When you retrieve self.canvas['width'], you are asking tkinter to give you the configured width of the widget, not the actual width. For the actual width you can use .winfo_width().

如果您想知道画布何时调整大小,您可以添加一个绑定到小部件上的 事件.传递给绑定的事件对象有一个 width 属性,该属性也有小部件的实际宽度.

If you want to know when the canvas is resized, you can add a binding to the <Configure> event on the widget. The event object that is passed to the binding has a width attribute which also has the actual width of the widget.

这是一个例子:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200, background="bisque")
canvas.pack(side="bottom", fill="both", expand=True)

canvas.create_text(10, 30, anchor="sw", tags=["event"])
canvas.create_text(10, 30, anchor="nw", tags=["cget"])

def show_width(event):
    canvas.itemconfigure("event", text="event.width: %s" % event.width)
    canvas.itemconfigure("cget", text="winfo_width: %s" % event.widget.winfo_width())

canvas.bind("<Configure>", show_width)

root.mainloop()

这篇关于tkinter 画布窗口大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆