python - Tkinter:create_window() 和框架未正确显示

标签 python user-interface python-2.7 tkinter

我正在使用 Python 和 Tkinter 开发一个小项目。我需要显示一个包含一些挖掘机/挖掘机的所有功能的表格。

表格基本上是一个大框架,里面有很多标签对象。我将此框架放入 Canvas 对象内(使用 create_window()),该对象位于另一个框架内(与滚动条一起)。

问题是我无法正确地可视化表格;我只能得到它的垂直部分:

enter image description here

绿色部分是包含Canvas对象和滚动条的框架

我发现解决这个问题的唯一方法是使用固定宽度......但这不是很好。 有什么建议吗?

编辑:

我希望 table 有固定的高度(并且这正在工作),正如您在此处看到的:

enter image description here

红色部分是 Canvas 对象,其中包含表格,绿色部分是框架,其中包含 Canvas 和滚动条。我删除了滚动条,以便更容易看到发生了什么。

问题是 Canvas 对象没有扩展(参见前面的屏幕截图),我不知道为什么。 我想要的是 Canvas 的宽度跟随表格的宽度。

代码在这里:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

import Tkinter, string, table
from functions import *

bg_color = "#d3d3d3"
first_table = True

# MODEL: Functions to handle the main processing of the program in
# response to user interaction
def create_tables():
    global tab, first_table, tab_space, mbtext
    select = choice.get()
    choices = [ 1, 2, 3, 4, 5]
    mbtext.set( str( choices[select])) # resetting the number in the menubutton
    if not first_table:
        # cleaning the canvas
        t.destroy()
        comp_space.destroy()
    # space to display the objects
    master = Tkinter.Frame( top, bg = 'green')
    master.grid( row = 2, column = 0, sticky = "wesn", padx = 10  )

    # space for the table:
    tab_space = Tkinter.Canvas( master, bg = 'red', highlightthickness = 0, height = 600, scrollregion=(0, 0, 2000, 780))
    tab_space.grid( row = 0, column = 0)

    # creating the table...
    tab = table.CompTable( tab_space, columns = choices[select]+1 )
    tab.first_set()
    tab_space.create_window(0, 0, anchor = "nw", window = tab)

    # and the scrollbar:
    scrollY = Tkinter.Scrollbar ( master, bg = bg_color, bd = 4, activebackground = bg_color, orient = "vertical")
    scrollY.grid( row = 0, column = 1, sticky = "nswe")

    #binding canvas and scrollbar together
    scrollY.configure( command = tab_space.yview)
    tab_space.configure(yscrollcommand = scrollY.set )

# VIEW: Setup the widgets

# The main window
top = Tkinter.Tk()
top.configure( bg = bg_color)
top.title("Comparatore")

# logo_frame/canvas - using a Canvas object to load images
logo_canvas = Tkinter.Canvas( top,  bg = bg_color, highlightthickness = 0, height = 58, width = 590 )
logo_canvas.grid( row = 0, column = 0, ipadx = 0, ipady=0, sticky = "nw")
logo = Tkinter.PhotoImage(file = "Images/Logo.gif")
logo_canvas.create_image(0, 0, image = logo, anchor="nw")

# background
bg_label = Tkinter.Label( top, bg = bg_color )
bg_label.grid( row = 1, column = 0, sticky = "nesw")

# menu to handle how many items we are using
select_text = Tkinter.Label( bg_label, text = " Selezionare il numero di macchine da confrontare: ", 
        font = ("verdana", 16), bg = bg_color)
select_text.grid( row = 0, column = 0, sticky = "nsew")

mbtext = Tkinter.StringVar()
mbtext.set("")
how_many_mb = Tkinter.Menubutton( bg_label, textvariable = mbtext, relief= "raised", bg = bg_color)
how_many_mb.menu = Tkinter.Menu( how_many_mb, tearoff = 0)
how_many_mb["menu"] = how_many_mb.menu
how_many_mb.grid( row = 0, column = 1, sticky = "nsew", padx = 4, ipadx = 18)

# CONTROLLER
choice = Tkinter.IntVar()
how_many_mb.menu.add_radiobutton( label = "1", variable = choice, value = 0, command = create_tables)
how_many_mb.menu.add_radiobutton( label = "2", variable = choice, value = 1, command = create_tables)
how_many_mb.menu.add_radiobutton( label = "3", variable = choice, value = 2, command = create_tables)
how_many_mb.menu.add_radiobutton( label = "4", variable = choice, value = 3, command = create_tables)
how_many_mb.menu.add_radiobutton( label = "5", variable = choice, value = 4, command = create_tables)


##
Tkinter.mainloop()

这是table模块的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

import Tkinter as tk

mbtext1 = tk.StringVar()
mbtext1.set("-Selezionare-")


details = ["Costruttore", "Modello", "Capacità Benna", "Carico rib. art.", "Peso", "Potenza",
                "Motore (Marca)", "Cilindrata", "Cilindri", "Alesaggio per corsa", "Regime di taratura",
                "Alimentazione aria", "Pompe", "Portata", "Pressione", "Trasmissione", "Marce",
                "Velocità traslazione", "Velocità di rotazione", "Differenziali", "Freni", "Pneumatici", "Passo", "Carreggiata",
                "Articolazione", " Raggio sterzo alla benna ", "Cinematismo benna", "Max altezza perno b.",
                "Forza di strappo", "Forza di penetrazione", "Sbalzo posteriore torretta", "Lama", "Larghezza benna", 
                "Larghezza max", "Altezza trasporto", "Larghezza cingoli", "Larghezza torretta",
                "Larghezza esterna pneumatici", "Lunghezza trasporto"]

class CompTable(tk.Frame):
    global details

    def __init__(self, parent, rows=len(details), columns=2):
        # using black background
        tk.Frame.__init__(self, parent, background="black")
        self._widgets = []
        for row in range(rows):
            current_row = []
            for column in range(columns):
                if row in [ 0, 1] and column != 0:
                    menu = tk.Menubutton(self, textvariable = mbtext1, width = 15)
                    menu.grid( row=row, column=column, sticky="nsew", padx=1, pady=1 )
                    current_row.append(menu)
                else:
                    label = tk.Label(self, background = "#fcfcfc", text="                           ", 
                                     borderwidth=0)
                    label.grid( row=row, column=column, sticky="nsew", padx=1, pady=1)
                    current_row.append(label)
            self._widgets.append(current_row)

    def set(self, row, column, value):
        widget = self._widgets[row][column]
        widget.configure(text=value)

    def first_set( self ):
        actual_detail = 0
        for element in details:
            self.set(actual_detail, 0, element)
            actual_detail += 1

最佳答案

尝试将其添加到表中,在tab_space.grid( row = 0, column = 0)之后立即创建代码:

master.columnconfigure(0, weight=1)

编辑

好的,这或多或少解决了所述问题:

如果更换

tab_space.grid( row = 0, column = 0)

tab_space.grid( row = 0, column = 0, sticky="nsew")
top.columnconfigure(0, weight=1)
master.columnconfigure(0, weight=1)

说明:

Tkinter grid几何管理器对小部件中的每一列和行都有一个“权重”。列/行的权重决定了该列或行占用小部件的分配空间的大小。

您可以更改给定列/行的权重。例如,如果您有一个名为 frame 的框架,然后frame.columnconfigure(3, weight=7)设置frame第3列的权重widget为7。有一个对应的函数叫rowconfigure .

默认权重为 0,这意味着列/行不会随着可用空间或所需空间的增加或减少而增大或缩小 - 它们是静态的。如果第 0 列的权重为 2,第 1 列的权重为 3,并且有 5 个额外像素可用,则第 0 列扩展 2 个像素,第 1 列扩展 3 个像素。

如果您只有一列,那么最后一位是无关紧要的,但此问题的重要部分是包含表格 Canvas 的列(以及包含主框架的列)具有非零 重量,因此网格几何管理器知道允许它扩展或收缩,而不是将其保持在最初分配的任何宽度。

Here is some documentation关于columnconfigurerowconfigure来自 NMT 的函数。兴趣点:columnconfigurerowconfigure实际上是 grid_columnconfigure 的别名和grid_rowconfigure ,我认为实现是为了节省 5 次击键。

注释:

您应该能够通过手动调整窗口大小来查看表格的其余部分。我认为您将不得不使用 <Configure> 做一些工作事件使窗口自动调整到正确的宽度。

关于python - Tkinter:create_window() 和框架未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875642/

相关文章:

JavaFX TilePane setPrefColumn/Row 方法不起作用?

c# - Windows 8 - 如何关闭触摸键盘?

python - 请解释这种意外的\b(退格)行为

java - 游戏面板实例的鼠标监听器

python - 异步Python程序中的条件if与twisted

python-2.7 - 创建 SVG 并将其保存到数据存储区(GAE + Python)

python - 错误 : could not find a version that satisfies the requirement tensorflow

Python 脚本在 IDLE Shell 和 Bash 中作为 .py 而不是 .exe 运行

python - 如何从 HTML 字符串中提取 IP 地址?

python - 如何定义在使用 nosetest 进行测试期间只调用一次的设置方法?