简体   繁体   English

如何在 python tkinter 中对齐小部件/列

[英]How to align widgets/columns in python tkinter

I am struggling to align some widgets in my tkinter project.我正在努力对齐我的 tkinter 项目中的一些小部件。 I want the label at the top of the window to be center aligned and the combobox to be under that label and right aligned.我希望 window 顶部的 label 居中对齐,combobox 位于 label 下方并右对齐。

I've been trying for a little while, but still can't get it working.我已经尝试了一段时间,但仍然无法正常工作。 I would really appreciate pointers from anyone who can tell where I've gone wrong.我非常感谢任何能告诉我哪里出错的人的指点。 I've attached my code and a screenshot to better illustrate the issue.我附上了我的代码和屏幕截图以更好地说明问题。

import sqlite3
import tkinter as tk
from tkinter import ttk

from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)

root = tk.Tk()

root.title("Solve Times Tracker")
root.configure(background="gray")
root.geometry("1200x800")

tk.Label(root, text="Solving time logger", font='ariel 17', anchor="w").grid(row=0,column=0,sticky="N")

options = ["one","two","three"]
combotext = tk.StringVar()
combotext.set('Please select your name')

select = ttk.Combobox(root, textvariable=combotext, state="readonly", font='ariel 17', width=25)

select.grid(row=1,column=1,sticky="E", pady=20)

select['values'] = ("one","two","three")


def callback_function(event):
    print('You selected:', combotext.get())

root.bind('<<ComboboxSelected>>', callback_function)



root.mainloop()

图片说明

Thanks.谢谢。

For your case, it is easier to use .pack() instead of grid() :对于您的情况,使用.pack()而不是grid()更容易:

tk.Label(root, text="Solving time logger", font='arial 17').pack()
...
select = ttk.Combobox(root, textvariable=combotext, state="readonly", font='arial 17', width=25)
select.pack(anchor='e', pady=20) # put at the right side
...

If you insist on using grid() :如果你坚持使用grid()

...
# make column 0 use all the horizontal space
root.columnconfigure(0, weight=1)

tk.Label(root, text="Solving time logger", font='arial 17').grid(row=0, column=0)
...
select = ttk.Combobox(root, textvariable=combotext, state="readonly", font='arial 17', width=25)
select.grid(row=1, column=0, sticky="e", pady=20)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM