为什么稍后声明的小部件首先出现?

2024-04-25 06:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的tkinter库来创建一个小型GUI。应用程序代码如下:

import tkinter as tk
from tkinter import ttk
APP_TITLE = "HiDE"

class Application(tk.Frame):
    """This class establishes an entity for the application"""
    #The constructor of this class
    def __init__(self, master=None):        
        tk.Frame.__init__(self,master)
        self.grid()

    def setupWidgets(self):
        self.message = tk.Label(self,text='Login')
        self.quitButton = tk.Button(self,text='Quit',command=self.quit)
        self.logButton = tk.Button(self,text='Login',command=self.quit)
        self.master.title(APP_TITLE)
        self.master.minsize("300","300")
        self.master.maxsize("300","300")
        self.message.grid()
        self.logButton.grid()
        self.quitButton.grid()

#Setting up the application
app = Application()
img = tk.PhotoImage(file='icon.png')
#getting screen parameters
w = h = 300#max size of the window
ws = app.master.winfo_screenwidth() #This value is the width of the screen
hs = app.master.winfo_screenheight() #This is the height of the screen

# calculate position x, y
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
#This is responsible for setting the dimensions of the screen and where it is placed
app.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
app.master.tk.call('wm', 'iconphoto', app.master._w, img)
app.master.i_con = tk.Label(app.master, image=img)
app.master.i_con.grid()
app.setupWidgets()  #<-- This is the function call
app.mainloop()

setupWidgets函数在设置映像后调用,但输出为:

The output


Tags: ofthetextselfmasterappimgis
1条回答
网友
1楼 · 发布于 2024-04-25 06:40:27

在用图像对标签进行网格化时,您已经在类中调用了Frame上的grid。这个类是放置其他小部件的地方,因此它与图像一起放置在标签的上方。你知道吗

而不是

app.master.i_con = tk.Label(app.master, image=img)

试试看

app.master.i_con = tk.Label(app, image=img)

将带有图像的标签与其他小部件放在框架中。你知道吗


另一方面,调用grid而不指定行和列是没有意义的。你知道吗

相关问题 更多 >