Horizontal Scrollbar not working in Python TKinter Frame - python

I have a canvas (for ttk.Frame not having xview,yview methods) holding frames inside of it, which I want to browse horizontally, as they are in the same row. Found some tutorials, and while they were dealing with different combination of widgets, I followed them, and tried to apply them to my problem, but with no success. I do see a scrollbar, but it doesn't do or respond to anything.
class App:
def __init__(self,db):
self.db = db
self.root = tkinter.Tk()
self.masterframe = ttk.Frame(self.root)
self.masterframe.grid()
self.mastercanvas = tkinter.Canvas(self.masterframe)
self.mastercanvas.grid()
self.scrollbar = ttk.Scrollbar(self.masterframe,orient="horizontal",
command = self.mastercanvas.xview)
self.scrollbar.grid()
self.mastercanvas.configure(xscrollcommand=self.scrollbar.set)
for i,e in enumerate(self.db.elements):
xf = XFrame(self,e)
xf.grid(row=0,column=i,sticky="n")
Edit:
class XFrame:
def __init__(self,app,x):
self.app = app
self.x = x
self.frame = ttk.Frame(self.app.mastercanvas)
self.set_up() # this sets frame's padding and populates it with widgets
Now, where ever I paste two lines of code here suggested* - at the end of the first init definition, or at the end of the second init definition - nothing new happens. I see my frames appearing as I intended them to appear - 3 of them. Part of the 4th. And an unfunctional scrollbar.
*
self.update_idletasks() # using self.root in first, self.app.root in second variant
self.mastercanvas.configure(scrollregion=self.mastercanvas.bbox("all"))
# in second variant reffered to as self.app.mastercanvas ...

You've got to configure the scrollregion attribute of the canvas so that it knows how much of the virtual canvas you want to scroll. This should do it:
# create everything that will be inside the canvas
...
# next, cause the window to be drawn, so the frame will auto-size
self.update_idletasks()
# now, tell the canvas to scroll everything that is inside it
self.mastercanvas.configure(scrollregion=self.mastercanvas.bbox("all"))
That being said, there's nothing in your canvas to be scrolled, and I'm not entirely sure what you were expecting to be in the canvas. If you are wanting to scroll through the instances of XFrame, they need to be children of some other frame, and that other frame needs to be an object on the canvas.

Related

How can I add custom Frame objects to custom ttk Notebook in Tkinter/python3?

I am creating a Tkinter/Python3 application where the main window inherits from Notebook (i need tabs), and each tab should be a custom class inheriting from Frame (I would then dynamically use matplotlib to create custom graphs).
Unfortunately I don't seem to be able to have Notebook accept my custom Frames.
Following very reduced snippet of code:
#!/usr/bin/env python3
from tkinter import *
from tkinter.ttk import Notebook
class MyFrame1(Frame):
def __init__(self, master=None, mytext=""):
super().__init__(master)
self.create_widgets(mytext)
def create_widgets(self, mytext):
self.label = Label(self.master, text=mytext, anchor=W)
# this is not placed relative to the Frame, but to the
# master
# 1. How I get the relative coordinates inside the frame
# to be 10, 10 of the frame area?
self.label.place(x=10, y=10, width=128, height=24)
class MyNotebook(Notebook):
def __init__(self, master=None):
super().__init__(master)
self.create_widgets()
def create_widgets(self):
self.f1 = MyFrame1(self, "abc")
# once the UI is drawn, the label "def" seems to overlay
# "abc" even when "f1" is selected
# 2. Why is self.f2 always shown even when self.f1 is
# selected?
self.f2 = MyFrame1(self, "def")
self.add(self.f1, text="f1")
self.add(self.f2, text="f2")
# Without this command nothing gets drawn
# 3. Why is this? Is this equivalent of 'pack' but for
# pixel driven layout?
self.place(width=640, height=480)
def main():
root = Tk()
root.minsize(640, 480)
root.geometry("640x480")
app = MyNotebook(master=root)
# this works as intended the label is indeed placed
# in the frame at 10, 10
#app = MyFrame1(master=root, mytext="123abc")
app.mainloop()
return None
if __name__ == "__main__":
main()
As per comments I have the following main question: why aren't my custom instances of MyFrame1 properly displayed inside MyNotebook?
Sub questions:
How can I get relative coordinate areas of where the frame is located when place my elements (in this case a Label)?
Why even when self.f1 tab is selected in the UI, I can still see the content of self.f2 tab?
Is self.place required in order to show all sub-elements when not using pack?
If I dynamically create Tkinter elements after the MyNotebook is initialized, will those be bound to respective tabs?
Not sure what I'm doing wrong?
Thanks!
Not sure what I'm doing wrong?
Your create_widgets method needs to add widgets to self, not self.master.
How can I get relative coordinate areas of where the frame is located when place my elements (in this case a Label)?
I don't understand what you mean by this. When you use place, coordinates will be interpreted relative to the frame. However, I strongly advise against using place. Both pack and grid will trigger the frame to resize to fit its children which almost always results in a more responsive UI
Why even when self.f1 tab is selected in the UI, I can still see the content of self.f2 tab?
Because you added internal widgets to self.master instead of self.
Is self.place required in order to show all sub-elements when not using pack?
No. It is required to use a geometry manager but it doesn't have to be place. Usually, place is the least desirable geometry manager to use. pack and grid are almost always better choices except for some very specific situations.
If I dynamically create Tkinter elements after the MyNotebook is initialized, will those be bound to respective tabs?
They will be in whatever tab you put them in.
Finally, I would suggest that you remove self.place in create_widgets. Instead, call pack, place, or grid in the same block of code that creates an instance of that class.
It's a bad practice for a widget to add itself to another widget's layout. The code that creates the widget should be the code that adds the widget to the layout.

Python Tkinter OOP Layout Configuration

I am trying to build an application with tkinter.
The layout works without OO principles, but I am struggling to understand how I should move it to OO.
The layout is as shown in the pic below. (1280x720px)
I have the following:
banner on top with username/welcome message, and logo rh corner, columnspan=8
menu bar with buttons on the left, split into 2 rows (row1: rowspan 6, row2: rowspan=4)
working area (white block) that has a Frame, which I'll add a notebook to, each menu button opening a different notebook page.
What is the best way to make this OO? (I am still learning, so very new to OO)
There is no straight translation possible, since everything depends on your needs.
If you create a simple programm you can just create the class and create every Button,Label,Frame... in the constructor. When created you have to choose one of the layout managers grid,pack or place. After that you create your functions and you are done. If you deal with bigger projects and have a big amount of Labels, Buttons etc.. you maybe want to create containers for each.
In your case you wont need a lot of functions and buttons, so you should maybe go with the basic approach:
from tkinter import *
class name_gui:
def __init__(self, top):
#specify main window
self.top = top
self.title = top.title("name_gui")
self.minsize = top.geometry("1280x720")
self.resizable = top.resizable(height=False,width=False)
#create buttons,Labels,Frames..
self.Button1 = Button(top,text="Button1",command=self.exa_fun)
self.Button2 = Button(top,text="Button2",command=self.exa_fun2)
#place them, choose grid/place/pack
self.Button1.place(relx=0.5,rely=0.5)
self.Button2.place(relx=0.5,rely=0.2)
#create your functions
def exa_fun(self):
pass
def exa_fun2(self):
pass
top = Tk()
exa_gui = name_gui(top)
top.mainloop()

How to position a ScrolledWindow (tkinter) scrollbar at the bottom

I am creating a gui with tkinter in python. I have created a scrollbar and this is what the section of code looks like:
beta_frame = Frame(width="500", height="680")
beta_frame.pack()
holder = ScrolledWindow(beta_frame, width=500, height=680)
holder.pack()
alpha_frame = holder.window
I would like to position this scrollbar at the very bottom every time something new is put on the screen (which would obviously be added to the bottom The only things I'm adding to the screen are labels and buttons), though I'm unsure how to do this and I've searched everywhere. All I came up with is the method see, which I am unsure if it is even applicable in this instance. Any help would be appreciated.
.see() is the normal way to get Tkinter to auto-scroll to a given position, but that method only exists on the widgets that have built-in support for scrolling - Listbox, Canvas, Text, and Entry. The Tix ScrolledWindow makes an ordinary Frame scrollable, so no such method will exist.
It appears that this line of code will do what you want:
holder.tk.eval(holder.vsb['command'] + " moveto 1.0")
vsb is the vertical scrollbar component of the ScrolledWindow, 'command' is the scrollbar configuration option that specifies a callback to invoke when the position is changed. This will refer to something deep inside Tix, but we don't care exactly what it is; we just invoke it with the same parameters that the scrollbar itself would, if being moved to the very end.

Displaying only one frame at a time in tkinter

I've been struggling with this for a while. I think I'm missing some simple piece of information and I hope you guys can help clear this up for me.
I'm trying to get tkinter to display different frames which I will eventually place widgets inside of. Here's what I did:
I've made a class that is supposed to initialize the window and make all the different frames the program will run.
I've made a separate class for each frame(I'm intending to have variables associated with the different classes when the program is done), and assigned a variable that will start that class up and make it run it's init function
I ended the StartUp class by telling it to tkraise() the frame I want displayed, and that's where things stop working correctly.
I set each frame to a different color, so when you run this program you will see that they split the screen space up instead of one being raised to the top. What am I missing?
One last point, I am purposely trying to spell everything out in my program, I learn better that way. I left it so I have to type tkinter.blah-blah-blah in front of each tkinter command so I can recognize them easily, and I decided not to have my classes inherit Frame or Tk or anything. I'm trying to understand what I'm doing.
import tkinter
class StartUp:
def __init__(self):
self.root = tkinter.Tk()
self.root.geometry('300x300')
self.container = tkinter.Frame(master=self.root, bg='blue')
self.container.pack(side='top', fill='both', expand=True)
self.page1 = Page1(self)
self.page2 = Page2(self)
self.page1.main_frame.tkraise()
class Page1():
def __init__(self, parent):
self.main_frame = tkinter.Frame(master=parent.container, bg='green')
self.main_frame.pack(side='top', fill='both', expand=True)
class Page2():
def __init__(self, parent):
self.main_frame = tkinter.Frame(master=parent.container, bg='yellow')
self.main_frame.pack(side='top', fill='both', expand=True)
boot_up = StartUp()
boot_up.root.mainloop()
When you do pack(side='top', ...), top doesn't refer to the top of the containing widget, it refers to the top of any empty space in the containing widget. Page initially takes up all of the space, and then when you pack Page2, it goes below Page1 rather than being layered on top of it.
If you are using the strategy of raising one window above another, you need to either use grid or place to layer the widgets on top of each other. The layering is something pack simply can't do.
Your other choice is to call pack_forget on the current window before calling pack on the new windowl

How do you create a LabelFrame with a scrollbar in Tkinter?

I'm using Python and Tkinter to create a GUI for a program I'm writing, and I'm having a couple of problems.
I have three objects descended from LabelFrame in an object descended from Frame. One of the LabelFrame descendants is two columns of corresponding Label and Entry objects.
The problem is that there are a varying number of Label and Entry pairs, and there can be more than fit on the screen. I need a way to make a scrollbar for this LabelFrame so that everything fits on the screen. I've tried various ways of making a Scrollbar object, but nothing seems to work. How can I bind a scrollbar to this frame?
Also, I need to be able to refresh or reload this LabelFrame when the load_message() method is called, but it just redisplays the new pairs on top of the old ones (so when there are less pairs in the new set, the old set is still visible at the bottom). I've tried using grid_forget() but either nothing changes or the whole frame doesn't display. How can I forget this display and then redisplay it?
Here is the code for this class:
class freq_frame(LabelFrame):
def __init__(self, master = None, text = 'Substitutions'):
LabelFrame.__init__(self, master, text = text)
self.grid()
def load_message(self):
self.frequency = get_freq(message)
self.create_widgets()
def create_widgets(self):
self.label_list = [Label(self, text = get_label(char, self.frequency[char]), justify = LEFT) for char in self.frequency.keys()]
self.entry_list = [Entry(self, width = 1) for char in self.frequency.keys()]
for n in range(len(self.label_list)):
self.label_list[n].grid(column = 0, row = n)
for n in range(len(self.entry_list)):
self.entry_list[n].grid(column = 1, row = n)
If anyone can help with either of these problems, I'd appreciate it.
Also, this question seems like it might be a little thin, but I don't know what to add. Don't hesitate to ask for more information (but be specific).
Thanks!
Labelframes don't support scrolling. So the short answer to your question is "you can't". It sounds obvious, but if the documentation for a widget doesn't say it supports scrolling, it doesn't support scrolling.
However, there is a simple solution. First, add a canvas as a child to the labelframe and pack it so that it fills the labelframe. Attach scrollbars to the canvas and add them to the labelframe too. Then embed a frame within the canvas, add your widgets to that inner frame, and then adjust the scrollregion of the canvas to match the size of the frame after you've added all the inner labels and entries.
It sounds complicated, but it's really very straight-forward.
As for re-creating the widgets when you call load_message, calling grid_forget only removes them from view, it doesn't actually destroy the widgets. Over time you could potentially end up with hundreds of non-visible widgets which is almost certainly not what you want.
Instead, you want to first destroy all the existing widgets. That's pretty easy if they all are in the same parent, since you can ask the parent for a list of all its children. Just iterate over that list to delete each child, then add any new children. An even easier solution is to destroy and recreate that inner frame that contains the labels and entries. When you delete a widget, all child widgets get automatically destroyed. So, delete that inner frame, create a new one, and add your labels and entries again.

Categories