Tkinter代码移入Frame容器后界面无显示问题求助
问题原因及解决方法
问题出在最后一行的InputFrame.place()调用——当你用place()布局容器却不指定位置和尺寸参数时,这个Frame的宽高会默认是0,里面的所有组件自然都显示不出来。
两种解决方式:
方式1:给place()添加参数,让Frame铺满窗口
把InputFrame.place()改成:
InputFrame.place(x=0, y=0, relwidth=1, relheight=1)
relwidth=1和relheight=1表示Frame的宽高占父容器(root)的100%,这样里面的组件就能正常显示了。
方式2:改用pack()布局(更简洁)
替换InputFrame.place()为:
InputFrame.pack(fill=BOTH, expand=True)
这种方式会自动让Frame填充整个可用空间,不需要手动设置位置和尺寸,是Tkinter里更常用的布局方式。
修改后的完整代码
from tkinter import * root = Tk() root.geometry('600x300') root.title('Input Frame') InputFrame = Frame(root, bg='lightblue') # label of the app title title = Label(InputFrame, text='Welcome to the Greeting App!', font=("Arial", 20, 'bold'), fg='blue', bg="lightblue" ) title.place(x=50,y=40) #label of the name taking and the entry box userlabel= Label(InputFrame, text='Enter your name...', font=("Arial", 10), bg="lightblue" ) userlabel.place(x=150,y=95) userentry = Entry(InputFrame, font=("Arial", 12) ) userentry.place(x=150,y=120) #now this is the menu of the dropping down, selection of color! selcolor = Label(InputFrame, text="Select a color...", font=("Arial", 10), bg="lightblue" ) selcolor.place(x=150,y=160) colors = [ "blue", "red", "yellow", "green", "black" ] #sel means selected, but shortened sel = StringVar() sel.set("black") menu = OptionMenu(InputFrame, sel, *colors) menu.place(x=150,y=185) #button for updating greetin' btn = Button(InputFrame, text='Update Greeting' ) btn.place(x=240,y=235) # 改用pack布局,或者用带参数的place InputFrame.pack(fill=BOTH, expand=True) # 或者 InputFrame.place(x=0, y=0, relwidth=1, relheight=1) root.mainloop()
内容的提问来源于stack exchange,提问作者saladbees
相关产品推荐
相关产品推荐

