在Tkinter Python中将子窗口相对于父窗口放置 [英] Placing child window relative to parent in Tkinter python

查看:754
本文介绍了在Tkinter Python中将子窗口相对于父窗口放置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含按钮的父窗口小部件。按下按钮后,我想直接在与该窗口小部件左侧对齐的父窗口小部件下方打开一个无边界(即没有Windows装饰按钮)窗口。我很困惑,设置窗口位置的唯一方法(看来)是使用 .geometry(),但更糟糕的是,我似乎无法获得绝对值父窗口小部件的坐标-我需要 .geometry(),仅是父窗口的父窗口的偏移量。到目前为止,我的代码是:

I have a parent widget which contains a button. When the button is pressed I would like to open a borderless (i.e. no Windows decoration buttons) window directly underneath the parent widget aligned to the left hand side of it. I'm puzzled that the only way (it seems) of setting the position of a window is using .geometry() but worse, I can't seem to get the absolute coordinates of the parent widget - which I need for .geometry(), only the offsets from the parent's parent. So far my code is:

# This is the child which appears when the button is pressed.
class ChildPopUpWindow(Frame):
    def __init__(self, parentWgdt):
        win = Toplevel(parentWgdt)
        geom = str(parentWgdt.winfo_x()) + '+' + str(parentWgdt.winfo_y() + parentWgdt.winfo_height())
        win.overrideredirect(1) # No win decoration.
        win.bd = 10
        win.relief = GROOVE
        win.geometry( geom )
        Frame.__init__(self, win)
        # etc. etc.

     # ... and this is the handler for the button being pressed.
     def onDropDown(self):
        popUp = ChildPopUpWindow(self)

此确实会弹出一个窗口,但相对于桌面,而不是父窗口小部件。据我所知,它似乎也没有考虑边框的厚度和浮雕。任何人都可以提供一种可以做到这一点的方法吗?是 .geometry()还是有更好的方法?

This does pop up a window but relative to the desktop, not to the parent widget. It also seems to take no account of the border thickness and relief as far as I can see. Can anyone offer a way that this can be done? Is .geometry() the way to go or are there better ways?

推荐答案

简单的答案是,使用 winfo_rootx winfo_rooty 获取相对于屏幕的坐标。是的, wm_geometry 是精确放置顶级窗口的方法。

The short answer is, use winfo_rootx and winfo_rooty to get the coordinates relative to the screen. And yes, wm_geometry is the way to place a toplevel window precisely.

例如:

    x = parentWgdt.winfo_rootx()
    y = parentWgdt.winfo_rooty()
    height = parentWgdt.winfo_height()
    geom = "+%d+%d" % (x,y+height)

作为一些友好的建议,我建议不要使用缩写var nms。这使代码难以阅读,尤其是在缩写错误的情况下(Wgdt至少应为Wdgt)。 geom geometry Wgdt 和 Widget 很小,但是可读性上的差异却很大。

As a bit of friendly advice, I recommend against abbrev var nms. It makes the code hard to read, especially when the abbreviation is wrong (Wgdt should at least be Wdgt). The difference in code size between geom and geometry, and Wgdt and Widget are tiny, but the difference in readability is huge.

这篇关于在Tkinter Python中将子窗口相对于父窗口放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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