@LayzyTeh

Что делать с разметкой в питон Tkinter?

Использую такой код:
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.init_main()
        
        
    def init_main(self):
        toolbar = tk.Frame(bg='#d7d8e0', bd=2)
        toolbar.pack(side=tk.TOP, fill=tk.X)
        
        
        self.toolbarForCanvas=tk.Frame(bg='#d7d8e0', bd=2)
        self.toolbarForCanvas.pack(side=tk.LEFT, fill=tk.Y)
        scrollBarGraph=tk.Scrollbar(master=self.toolbarForCanvas)
        scrollBarGraph.pack(side=tk.RIGHT)
        
        btnOpenDialog = tk.Button(toolbar, text='open', command=self.draw, bg='#d7d8e0', bd=0, compound=tk.TOP)
        btnOpenDialog.pack(side=tk.RIGHT)
        
        
        btnSaveDialog = tk.Button(toolbar, text='save', command=self.save, bg='#d7d8e0', bd=0, compound=tk.TOP)
        btnSaveDialog.pack(side=tk.LEFT)
        
        
        self.txtToEntryName=tk.Entry(toolbar,width=20)
        self.txtToEntryName.pack(side=tk.LEFT)
        
        
        self.lablTime=tk.Label(toolbar,text='time:......',padx=60)
        self.lablTime.pack(side=tk.LEFT)
        
        
    def save(self):
        s=self.txtToEntryName.get()
        plt.savefig(s,dpi=150)
        
        
    def draw(self):
       nazvania=['OH','IM','DMI','TMD','QMT','PMQ','SMP','AMS','EWI','NWD','TWT','TWQ','DWP','TWS','FR','PL']
       plot=['0H',"1M",'2C1','3C2','4C3','5C4','6C5','7C6','8w1','9w2','10w3','11w4','12w5','13w6','14R','15L']
       for i in range(16):
           exec(f"""
{nazvania[i]}=[]
with open("/home/biotech/Documents/EEG/gur1/sinh{plot[i]}.txt",'r') as q:
    for i in q.readlines():
        {nazvania[i]}.append(float(i[:-2]))
t=1/2000
fig{nazvania[i]}=plt.figure()  
plt.axhline(-0.1,0,2*t*len({nazvania[i]}),color="black")
Y=np.array({nazvania[i]})
X=np.linspace(0,t*len(Y),len(Y))
plt.scatter(X,Y,s=1,color="black")


fig{nazvania[i]}.set_size_inches(t*len(Y)*3,0.5)
canvas{nazvania[i]} = FigureCanvasTkAgg(fig{nazvania[i]}, master=self.toolbarForCanvas)  # A tk.DrawingArea.

#canvas{nazvania[i]}.draw()
canvas{nazvania[i]}.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
""")
        #self.lablTime.config(text='time:'+str(t*len(Y)))

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.title("EEG ver.gragh")
    root.geometry("1000x600")
    root.resizable(False, False)
    root.mainloop()


заместо того чтобы исользовать размер set_size_inches(t*len(Y)*3,0.5) сжимает по Y хотя был добавлен Scrollbar
5da8945f65928645358683.png

что надо сделать для того чтобы скроллбар был к рамке с графиками
  • Вопрос задан
  • 193 просмотра
Решения вопроса 1
NeiroNx
@NeiroNx
Программист
Вот стандартный пример, который работает:
from tkinter import *   # from x import * is bad practice
from tkinter.ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы