执行python代码时,gui为空

2024-04-20 03:24:44 发布

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

每当我执行此代码时,gui上都不会显示任何内容。如果我使用网格来放置标签和按钮,效果会很好。如果我用的话它什么也看不出来。一个地方一个地方贴标签。你知道吗

from Tkinter import *


class Applet(Frame):
""" First attempt to make the program """
    def __init__(self, master):
            """ initialize the frame """
            Frame.__init__(self,master)
            self.login()
    #self.Signup()
    def login(self):
            self.Login_username = StringVar()
            self.Login_password = StringVar()
            self.Label1 = Label(self, text = 'Username: ').place(x = 0, y = 0)
            self.Label2 = Label(self, text = 'Password: ').place(x =50, y = 0)
            self.loguser = Entry(self, textvariable = self.Login_username, width = 15).place(x = 0, y = 10)
            self.logpass = Entry(self, textvariable = self.Login_password, width = 15, show = '*').place(x = 50, y = 10)
            self.button = Button(self, text = 'Login').place(x = 400, y = 0)



Top = Tk()
Top.title('test-gui')
app = Applet(Top)
Top.geometry('700x350')
Top.mainloop()

Tags: thetextselfmasterinittopdef地方
1条回答
网友
1楼 · 发布于 2024-04-20 03:24:44

您只是创建了一堆对象,并将它们添加到一个本身没有添加到任何地方的接口中。你知道吗

将它们添加到接口的最简单方法是调用Applet上的pack方法。你知道吗

不过,你还是会有一些问题。你知道吗

首先,您试图显式地place将所有元素几乎放在彼此的顶部,因此它们都将重叠成一团。你知道吗

其次,place方法返回None,因此所有成员变量都将是None,而不是实际的小部件。你知道吗

以下是解决所有三个问题的版本:

from Tkinter import *

class Applet(Frame):
    """ First attempt to make the program """
    def __init__(self, master):
            """ initialize the frame """
            Frame.__init__(self,master)
            self.login()
    #self.Signup()
    def login(self):
            self.Login_username = StringVar()
            self.Login_password = StringVar()
            self.Label1 = Label(self, text = 'Username: ')
            self.Label1.place(x = 0, y = 0)
            self.Label2 = Label(self, text = 'Password: ')
            self.Label2.place(x = 100, y = 0)
            self.loguser = Entry(self, textvariable = self.Login_username, width = 15)
            self.loguser.place(x = 0, y = 20)
            self.logpass = Entry(self, textvariable = self.Login_password, width = 15, show = '*')
            self.logpass.place(x = 100, y = 20)
            self.button = Button(self, text = 'Login')
            self.button.place(x = 400, y = 20)

Top = Tk()
Top.title('test-gui')
app = Applet(Top)
app.pack(fill='both', expand=True)
Top.geometry('700x350')
Top.mainloop()

但是,通常最好使用box和pack方法,而不是显式调用place。例如,x = 100而不是x = 50等,在我的系统上工作,使所有内容都很好地布局,但是如果您的系统有不同的默认字体大小、小部件边界等,它最终将重叠或奇怪地隔开。你知道吗

相关问题 更多 >