【问题标题】:How do I change the width of Tkinter widgets in smaller increments (Python)?如何以较小的增量更改 Tkinter 小部件的宽度(Python)?
【发布时间】:2020-11-14 14:16:46
【问题描述】:

box 的左侧与some_label 的左侧对齐。我无法设置宽度,使some_label 的右侧也与box 的右侧对齐,因为不同宽度值之间的增量太大。 35 的width 使some_label 的右端太靠左,而 36 的width 使其太靠右。

from tkinter import *
root = Tk()

root.geometry('500x500')

box = Frame(root, width=383, height=246, bg='black')

box.place(x=241, y=65, anchor=CENTER)

some_label = Label(root, text='Some Label', borderwidth=1, relief='solid')

some_label.place(x=50, y=210)

some_label.config(width=35, font=('TkDefaultFont', 15))  # whether width is 35 or 36, the label never aligns with the box

mainloop()

【问题讨论】:

    标签: python tkinter widget label width


    【解决方案1】:

    由于使用place(),所以可以直接指定宽度:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry('500x500')
    
    box = tk.Frame(root, width=383, height=246, bg='black')
    box.place(x=241, y=65, anchor='c')
    
    some_label = tk.Label(root, text='Some Label', borderwidth=1, relief='solid')
    some_label.place(x=241, y=210, width=383, anchor='c') # set width to same as 'box'
    some_label.config(font=('TkDefaultFont', 15))
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      要以像素为单位设置标签的宽度,您必须包含图像。最简单的方法是使用透明像素并将其显示在带有compound='center' 的标签中,它不会偏移文本。

      或者,您可以简单地使用包含框架来控制小部件的大小。

      我在示例中包含了这两种方式。

      from tkinter import *
      
      root = Tk()
      root.geometry('500x500')
      
      box = Frame(root, width=383, height=246, bg='black')
      box.place(x=241, y=65, anchor=CENTER)
      
      some_label = Label(root, text='Some Label', borderwidth=1, relief='solid')
      some_label.place(x=50, y=210)
      img = PhotoImage(file='images/pixel.gif')       # Create image
      some_label.config(image=img, compound='center') # Set image in label
      some_label.config(width=379, font=('TkDefaultFont', 15))    # Size in pixels
      
      # Alternateivly control size by an containing widget:
      container = Frame(root, bg='tan')   # Let frame adjust to contained widgets
      container.place(x=241, y=360, anchor=CENTER)
      # Let the contained widget set width
      other_box = Frame(container, height=100, width=383, bg='black') # Set width
      other_box.pack()
      other_label = Label(container, text='Some Label', borderwidth=1, relief='solid')
      other_label.pack(expand=True, fill=X, pady=(20,0))  # Expand to fill container
      other_label.config(font=('TkDefaultFont', 15))
      
      mainloop()
      

      如果您要进行复杂的 GUI 设计,grid() 几乎总是更容易使用。

      【讨论】:

        猜你喜欢
        • 2013-08-29
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-10
        • 2018-09-03
        • 2017-10-18
        相关资源
        最近更新 更多