python中的Tkinter grid()对齐问题

2024-06-25 23:29:11 发布

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

我第一次在python中工作,基本上我试图让这些标签在正确的列和正确的行中对齐,但是由于某些原因它没有向下移动,列也不正确。任何帮助都将不胜感激!在

代码:

    from tkinter import *
    import sys

    #Setup GUI

    #Create main window
    main = Tk();
    #Create title of main window
    main.title = "Waterizer 1.0";
    #Create default size of main window
    main.geometry("1024x768");
    #Lets get a fram to stick the data in we plan on using
    mainApp = Frame(main);
    #Snap to grid
    mainApp.grid();
    #Font for main labels
    labelFont = ('times', 20, 'bold');
    #Label for the Power
    powerLabel = Label(mainApp, text="Power  Status");
    powerLabel.config(fg="Red", bd="1");
    powerLabel.config(font=labelFont);
    powerLabel.grid( row=0,column=20,columnspan=4, sticky = W);
    #Label for Water
    waterLabel = Label(mainApp, text="Water Status");
    waterLabel.config(fg="Blue", bd="1");
    waterLabel.config(font=labelFont);
    waterLabel.grid(row=20, column=20, columnspan=4, sticky = W);

现在我将附上一张图片给你们看它是如何显示的。。。哪个是不正确的:-(

 Issue with the grid.


Tags: oftoimportconfigfortitlemaincreate
2条回答

空行的高度为零,空列的宽度为零。由于第1-19行中没有小部件,第0-19列中也没有小部件,所以网格的行为与您的代码设计的一样。在其他行和列中放一些东西,你的标签就会移动。在

如果一行或一列不包含任何内容,那么它的大小是1个像素,非常小。您在输出中看到的实际上是相隔20行的两个文本。添加小部件,您将看到您的结果。在

您还可以使用grid_rowconfiguregrid_columnconfiguresticky属性来指定网格中小部件的拉伸方式。这样你就可以把你的小部件放在正确的屏幕位置。在

有关如何使用网格属性的详细信息,请参阅我的答案:Tkinter. subframe of root does not show

为了更好地理解网格,我在代码中添加了另一个小部件:

from tkinter import *
import sys
from tkinter.scrolledtext import ScrolledText

#Setup GUI

#Create main window
main = Tk()
#Create title of main window
main.title = "Waterizer 1.0"
#Create default size of main window
main.geometry("1024x768")
#Lets get a fram to stick the data in we plan on using
mainApp = Frame(main)
#Snap to grid
mainApp.grid(row=0, column=0, sticky='nsew')
#main grid stretching properties
main.grid_columnconfigure(0, weight=1)
main.grid_rowconfigure(0, weight=1)
#Font for main labels
labelFont = ('times', 20, 'bold')
#Label for the Power
powerLabel = Label(mainApp, text="Power  Status")
powerLabel.config(fg="Red", bd="1")
powerLabel.config(font=labelFont)
powerLabel.grid( row=0,column=20, sticky = W)
#Label for Water
waterLabel = Label(mainApp, text="Water Status")
waterLabel.config(fg="Blue", bd="1")
waterLabel.config(font=labelFont)
waterLabel.grid(row=20, column=20, sticky = W)
#ScrollText to fill in between space
ScrollText = ScrolledText(mainApp)
ScrollText.grid(row=1, column=20,sticky = 'nsew')
#mainApp grid stretching properties
mainApp.grid_rowconfigure(1, weight=1)
mainApp.grid_columnconfigure(20, weight=1)

main.mainloop()

试试这个。在

PS:在python的每一行后面不需要;

相关问题 更多 >