python tkinter子窗口_在Tkinter Python中将子窗口相对于父窗口放置

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)

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?

解决方案

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.

For example:

x = parentWgdt.winfo_rootx()

y = parentWgdt.winfo_rooty()

height = parentWgdt.winfo_height()

geom = "+%d+%d" % (x,y+height)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值