如何始终将标签重叠居中显示

0 投票
1 回答
43 浏览
提问于 2025-04-12 15:00

在我的代码里,有一些复选框可以选择要打印的数据。但是如果我使用 .place 方法,并且取消勾选某些框,就会导致显示之间出现空隙。例如:

有空隙的标签

但是,如果我使用 pack() 方法,代码就会被固定在窗口的顶部。例如:

标签在屏幕顶部

我该怎么做才能让它们始终重叠在一起,同时又居中显示呢?

相关问题:

1 个回答

0

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者报错。这种时候,我们可以去一些技术论坛,比如StackOverflow,去寻找解决方案或者向其他人请教。

在这些论坛上,很多人会分享他们的经验和解决方案,帮助其他人解决类似的问题。你可以看到很多不同的代码示例和解释,这些都是为了让大家更容易理解。

如果你在学习编程,遇到困难,不妨去这些地方看看,可能会找到你需要的答案。

from tkinter import *

#functions

def get_distance_travelled():
    # your code to find the distance travelled. I have given a dummy value
    return 15 #Remove this line and change according to yours
    
def get_max_height():
    #your code to find max_height. I have given a dummy value
    return 100 #Remove this line and change according to yours

def get_final_velocity():
    # your code to get final velocity. I have given a dummy value
    return 1000 #Remove this line and change according to yours
    
def get_flight_time():
    # your code to get flight_time.I have given a dummy value
    return '10:10' #Remove this line and change according to yours
    
def show_items():
    pop = Toplevel(root)
    pop.geometry('300x200')
    fn_lst = [get_distance_travelled(), get_max_height(), get_final_velocity(), get_flight_time() ]
    for i in range(len(ls)):
        if vardct[i].get()==1:
            
            # Remove the word 'Display ' from Display texts
            txt = keydct[i].replace('Display ', '')
            Label(pop, text=f'{txt} : {fn_lst[i]}').pack()

#design

root = Tk()
root.geometry('300x200')


# list containing display texts
ls =    ['Display Distance Travelled', 
         'Display Max Height',
        'Display Final Velocity',
        'Display Flight Name']
        
        
# Create 3 dicts say for display texts, intvars, and wdgts
keydct, vardct, wdgdct = {}, {}, {}

#create widgets and pack
for i in range(len(ls)):
    keydct[i] = ls[i]
    vardct[i] = IntVar()
    wdgdct[i] = Checkbutton(root, text = keydct[i], variable = vardct[i])
    wdgdct[i].pack() 


    
     
    
btn = Button(root, text = 'Show', command=show_items)
btn.pack()
root.mainloop()

撰写回答