Tkinter基本布局与文本

时间:2016-03-28 21:12:22

标签: python tkinter

我正在为基于文本的游戏的基本布局而苦苦挣扎。为什么第一列中的文本在字符串结尾之前停止,为什么窗口太高?以下代码,任何帮助表示赞赏。

from Tkinter import *
import tkFont

class TreasureHunt:

    def __init__(self, master):
        app = Frame(master)
        app.grid()

        self.mono_font = tkFont.Font(family="monospace",size=24,weight="bold")
        self.instructions = "Find the hidden treasure!\n\nUse the arrow keys to select where to look, then press Enter to check. \
        There is a 50/50 chance you will be told the distance from the treasure. Keep hunting until you find it. Good luck!"

        self.info = Text(app, wrap=WORD, padx=10, pady=10, bd=0,width=10)
        self.info.insert(1.0,self.instructions)
        self.info.grid(row=0,column=0,sticky=N)

        self.island = Text(app, bg="cyan",bd=0, padx=20, pady=20, font=self.mono_font,width=20)
        self.island.insert(1.0, "ready")
        self.island.grid(row=0,column=1)

        self.display_grid()

    def display_grid(self):
        self.matrix = [["# " for col in range(8)] for row in range(8)]
        for row in range(len(self.matrix)):
            row_str = "".join(self.matrix[row]) +"\n"
            self.island.insert(1.0,row_str)


root = Tk()
game = TreasureHunt(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

窗口太高的原因是因为你没有给出明确的高度,所以Tkinter必须依赖它的默认值。默认情况下,文本小部件将为24行高。

右侧的小部件使用最高的字体,使其成为窗口中最高的小部件。该窗口将尝试适合所有内容,因此如果您使该文本小部件更小,整个窗口将更小。

self.island = Text(app, ..., height=9)

我不太清楚你在“字符串结尾之前的第一列[停止]中的文字”。我没有看到它停止,我看到它正如我所期望的那样包裹,就像你指示它一样。您设置了10个字符的宽度,并告诉它在单词边界处换行。

此外,当您使用grid时,根据经验,您必须至少为一行和一列提供权重。权重是Tkinter如何分配任何额外空间的重要性。请注意,如果调整窗口大小,内部的小部件不会增大或缩小。这是因为它们所在的行和列的默认权重为0(零)。

要进行更改,请使用row_configurecolumn_configure。例如,如果您希望蓝色区域扩展以占用所有额外空间,请为其行和列指定权重为1(一):

app.grid_rowconfigure(0, weight=1)
app.grid_columnconfigure(1, weight=1)

如果你这样做,你会发现.....没有任何变化。 Tkinter确实会为第0行和第1列提供额外的空间。但是,你必须做的更多。在调用sticky时,您需要使用grid属性来请求窗口小部件“粘住”给定空间的边缘。

self.info.grid(row=0,column=0,sticky=N+S+E+W)
...
self.island.grid(row=0,column=1,sticky=N+S+E+W)

当你这样做时,你会看到......没有任何变化。这是因为app是一个框架,并且该框架位于根窗口内。但是,您没有为app所在的行和列指定权重,而且您也没有为其指定sticky值。

但是,如果您的根窗口只有一个小部件,那么使用pack而不是网格会更容易一些。我说这个的原因是你不必担心设置行和列的权重。

尝试更改此行:

app.grid()

......对此:

app.pack(fill="both", expand=True)

有了这个,你会看到现在窗口小部件填满了窗口,如果你调整窗口大小,它就会相应调整大小。

作为一项有趣的练习,请尝试在设置应用重量的位置添加此行。将其他行留在那里,你想给两个列一个权重。试一试,注意手动调整窗口大小时会发生什么。

app.grid_columnconfigure(0, weight=1)

请注意,两个内部小部件都会扩展。柱子具有相同的重量,因此它们可以均匀扩展。要获得向左扩展两倍的权利,请将其权重设置为2.