Вопрос

I have a problem in specifying Entry widget size on Linux and Windows. These entries were created on Linux:

On Linux, they look fine within the Text widget. There are 2 Entry cells one by one, created with this line of code:

tk.Entry(master, width=16)

The width is specified as being 16 characters long.

However, on Windows the cells take up only a half of the space and I have to specify the width of 22, because font size is smaller on Windows.

My question is: is there a way to specify a relative width of these two cells in the Text widget, so each cell takes 1/2 of the parent widget?

Это было полезно?

Решение

Within a text widget? No, there is no direct support for relative widths. within a frame? yes. If you are putting them in a text widget (I presume, so you can scroll them) you have to manage the widths yourself. You can add a binding to the <Configure> event of the text widget. This fires when the text widget changes size, and you can resize all the widgets at that point.

The easiest thing is to put them in a frame using grid, then put the frame in a canvas so you can scroll it.

Here's an example:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.canvas = tk.Canvas(self, width=200, highlightthickness=0)
        self.vsb = tk.Scrollbar(orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)

        self.container = tk.Frame(self.canvas, borderwidth=0, highlightthickness=0)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.grid_columnconfigure(1, weight=1)
        for i in range(30):
            e1 = tk.Entry(self.container)
            e2 = tk.Entry(self.container)
            e1.grid(row=i, column=0,sticky="ew")
            e2.grid(row=i, column=1,sticky="ew")
            e1.insert(0, "find %s" % i)
            e2.insert(0, "replace %s" % i)

        self.canvas.create_window((0,0), anchor="nw", window=self.container, tags="container")
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        self.canvas.bind("<Configure>", self.OnCanvasConfigure)

    def OnCanvasConfigure(self, event):
        self.canvas.itemconfigure("container", width=event.width)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top