有没有办法克隆 tkinter 小部件? [英] Is there a way to clone a tkinter widget?

查看:39
本文介绍了有没有办法克隆 tkinter 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建小部件网格.这个小部件网格从告诉我它们坐标的标签开始.然后我有一个将替换它们的按钮的起点和终点列表.假设我有一个从 (0, 0) 到 (0, 2) 的按钮,我从这个位置移除标签并在那里放置一个具有正确行跨度的按钮.如果一个按钮将替换另一个按钮(不仅仅是一个标签),我创建一个框架,然后我想克隆该按钮作为更改父级的一种方式(我已经读过这不是 tkinter 的可能性)并添加框架上的新按钮也是如此.然后框架将用并排的按钮而不是重叠的按钮替换网格上的小部件(标签和旧按钮).

I'm trying to create of grid of widgets. This grid of widgets starts out as labels telling me their coordinates. I then have a list of starting and ending points for buttons that will replace them. Say I have a button that will go from (0, 0) to (0, 2), I remove the labels from this location and put a button there with the correct rowspan. If a button will be replacing another button (not just a label), I create a frame, then I want to clone the button as a way of changing the parent (which I've read is not a possibility with tkinter) and add the new button to the frame as well. The frame will then replace the widgets (labels and old buttons) on the grid with the buttons side by side instead of overlapping.

所以这个 示例图片 显示了一个标签网格,然后第一个按钮的位置放置,然后第二个按钮应该去的地方,以及两个按钮并排在其中的结果框架.

So this example image shows a grid of Labels, then where the first button is placed, then where the second button should go, and the resulting frame with both buttons in it side by side.

对我来说最大的问题是必须删除第一个按钮并将其重新放置在网格上,因为无法更改小部件的父级.尽管我也欢迎关于在网格上并排放置按钮的更好想法.

The big issue for me is having to remove the first button and re-place it on the grid because it's not possible to change the parent of a widget. Although I'm welcome to better ideas on getting buttons side by side on the grid as well.

推荐答案

没有直接的方法来克隆小部件,但是 tkinter 提供了一种方法来确定小部件的父级、小部件的类以及所有小部件的配置值.此信息足以创建副本.

There is no direct way to clone a widget, but tkinter gives you a way to determine the parent of a widget, the class of a widget, and all of the configuration values of a widget. This information is enough to create a duplicate.

它看起来像这样:

def clone(widget):
    parent = widget.nametowidget(widget.winfo_parent())
    cls = widget.__class__

    clone = cls(parent)
    for key in widget.configure():
        clone.configure({key: widget.cget(key)})
    return clone

这篇关于有没有办法克隆 tkinter 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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