【问题标题】:Position childs inside a paned window将孩子定位在窗格窗口内
【发布时间】:2021-09-04 12:50:31
【问题描述】:

我正在尝试实现一个可调整大小的窗口,其中包含一些小部件,其中一些应该居中,一些应该左对齐。目前,所有小部件都居中:

from tkinter import *

root = Tk()

root.resizable()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_cordinate = int((screen_width / 2) - (300 / 2))
y_cordinate = int((screen_height / 2) - (200 / 2))
root.geometry("{}x{}+{}+{}".format(300, 200, x_cordinate, y_cordinate))
root.title("Pane Sticky Test")

main_pane = PanedWindow(root, orient=VERTICAL)
main_pane.pack(fill=BOTH, expand=1)

var = IntVar()

# check = Checkbutton(main_pane, text="My option", variable=var, sticky=W) --> error unknown option "-sticky"
check = Checkbutton(main_pane, text="My option", variable=var)
main_pane.add(check)

# label = Label(main_pane, text="Preview:", sticky=W) --> error unknown option "-sticky"
label = Label(main_pane, text="Preview:")
main_pane.add(label)

entry = Text(main_pane, height=10, width=50)
main_pane.add(entry)
root.mainloop()

我想将我的选项复选框和我的预览标签左对齐。我在this documentation 中读到,应该有一个粘性选项“功能类似于 .grid() 方法的粘性参数”。但是这个选项不起作用(见我注释掉的两行)。

有没有办法将一些小部件左对齐或右对齐放置在 tkinter 的垂直方向的窗格窗口中?我在 Windows 上使用 tkinter 8.6 版和 Tcl/Tk 8.6.9 版。

【问题讨论】:

    标签: python tkinter sticky


    【解决方案1】:

    有一个名为anchor 的选项,其功能类似于sticky

    为小部件添加anchor 参数。例如 -

    check = Checkbutton(main_pane, text="My option", variable=var,anchor=W)
    

    你会看到复选按钮在左边。

    最终代码-

    from tkinter import *
    
    root = Tk()
    
    root.resizable()
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x_cordinate = int((screen_width / 2) - (300 / 2))
    y_cordinate = int((screen_height / 2) - (200 / 2))
    root.geometry("{}x{}+{}+{}".format(300, 200, x_cordinate, y_cordinate))
    root.title("Pane Sticky Test")
    
    main_pane = PanedWindow(root, orient=VERTICAL)
    main_pane.pack(fill=BOTH, expand=1)
    
    var = IntVar()
    
    check = Checkbutton(main_pane, text="My option", variable=var,anchor=W)
    main_pane.add(check)
    
    label = Label(main_pane, text="Preview:",anchor=W)
    main_pane.add(label)
    
    entry = Text(main_pane, height=10, width=50)
    main_pane.add(entry)
    root.mainloop()
    

    并且不要使用 * 进行导入。更推荐这种方式 - import tkinter as tk 即使用别名导入

    参考 - anchorwhy use import tkinter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2015-08-05
      • 1970-01-01
      相关资源
      最近更新 更多