我正在使用Tkinter创建一个GUI,并且已经使用ttk.Notebook()创建了多个选项卡。在Tab1上有一些Labels和Entry框,在Tab2上有matplotlib图。我只在使用网格布局管理器。
我遇到的问题是,当我将绘图放置在Tab2上(行= 0)时,它似乎也增加了Tab 1上第0行的大小,从而在2个标签之间创建了很多空间(应该在另一个之上)。
(非常)下面是该代码的最低版本。我想念什么?如何独立控制每个选项卡上的行高,以便Tab2上的小部件不设置Tab1上的行高?预先感谢您的帮助。
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.figure import Figure
matplotlib.use("TkAgg")
class MainGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title('Title')
self.geometry('750x500')
# Adds tabs to main window
self.nb = ttk.Notebook(self)
self.nb.grid(row=0, column=0, columnspan=5, rowspan=4, sticky='NESW')
self.tab1 = ttk.Frame(self.nb)
self.nb.add(self.tab1, text='Tab1')
self.tab2 = ttk.Frame(self.nb)
self.nb.add(self.tab2, text='Tab2')
# defines a grid 10 x 5 cells in the main window & tabs
rows = 0
cols = 0
while rows < 10:
while cols < 5:
self.rowconfigure(rows, weight=1)
self.columnconfigure(cols, weight=1)
self.tab1.rowconfigure(rows, weight=1)
self.tab1.columnconfigure(cols, weight=1)
self.tab2.rowconfigure(rows, weight=1)
self.tab2.columnconfigure(cols, weight=1)
cols += 1
rows += 1
self.tab1Label = tk.Label(self.tab1, text="This is a Label")
self.tab1Label.grid(column=0, row=0, sticky='NW')
self.tab1Label2 = tk.Label(self.tab1, text="This is also a Label")
self.tab1Label2.grid(column=0, row=1, sticky='NW')
self.makePlot()
def makePlot(self):
f = Figure(figsize=(5, 5), dpi=100)
a = f.add_subplot(111)
a.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5])
canvas = FigureCanvasTkAgg(f, self.tab2)
canvas.draw()
canvas.get_tk_widget().grid(column=2, row=0, columnspan=2, sticky='NSEW')
def main():
MainGUI().mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
如果您将此行注释掉:
self.tab1.rowconfigure(rows, weight=1)
您会发现问题已消失。您的问题来自您的while
循环。我也可以说您的while
循环没有按照您认为的那样做。您只需将第0行配置为具有权重,这就是为什么第二个标签位于屏幕底部的原因。
让我们细分您的while
语句在做什么。
在第一个循环row = 0
上,您告诉该循环基于while
进行另一个cols
循环。因此,它执行了rowconfigure(0, weight=1)
5次,也执行了columnconfig(0 through 4, weight=1)
。但是问题出在下一个循环。因为cols = 5
现在您的第二while循环将始终为false,因此永远不会配置第1到9行。
您应该做的就是这样。
for i in range(10):
self.tab1.rowconfigure(i, weight=1)
self.tab2.rowconfigure(i, weight=1)
for i in range(5):
self.tab1.columnconfigure(i, weight=1)
self.tab2.columnconfigure(i, weight=1)
这样,您可以确保对所有行和列都施加权重。