I am having this issue where the scroll bar is not displaying on the listbox. I do not know what the issue is as.
I believe the issue is originating from the Scrollbar variables as the Listbox appears to be displaying and functioning properly.
The output is displaying the listbox with no scrollbar on the right (as set)
Here is the Listbox with the for loop however, it is displaying the wrong dimensions
Here is the code:
#imports
from tkinter import *
from tkinter import messagebox as ms
from tkinter import ttk
import sqlite3
from PIL import Image,ImageTk
import datetime
global time
time = datetime.datetime.now()
class main:
def __init__(self,master):
self.master = master
def search_user_sql(self):
self.search_user_sqlf = Frame(self.master, height=300, width =200)
scrollbar = Scrollbar(self.search_user_sqlf)
scrollbar.pack(side = RIGHT,fill = BOTH)
myList = Listbox(self.search_user_sqlf, yscrollcommand= scrollbar.set)
myList.pack( side = LEFT, fill = BOTH, expand = 2)
scrollbar.config( command = myList.yview )
self.search_user_sql()
root = Tk()
root.title("Gym Membership System")
main(root)
root.mainloop()
You need to pack the frame to display it. To pack() the frame with the correct size settings, try:
search_user_sqlf = Frame(master, height=300, width=200)
search_user_sqlf.pack(expand=True, fill='both')
search_user_sqlf.pack_propagate(0)
Here is how to attach a scrollbar to list set in a frame in Tkinter:
from tkinter import *
master = Tk()
search_user_sqlf = Frame( master, width=400, height=400)
search_user_sqlf.pack(expand=True, fill='both')
search_user_sqlf.pack_propagate(0)
scrollbar = Scrollbar(search_user_sqlf)
scrollbar.pack(side=RIGHT, fill=Y)
myList = Listbox(search_user_sqlf, yscrollcommand=scrollbar.set)
for line in range(100):
myList.insert(END, "This is line number " + str(line))
myList.pack( side = LEFT, fill = BOTH , expand = 2)
scrollbar.config( command = myList.yview )
mainloop()
Related
I am making a random generator for my friends and I'm stuck trying to make a scroll down option. So if you generate more the window can show, a scroll down window should be possible. But I can't seem to get any to work. I've tried many online tutorials.
And my second issue with my code is that I can't clear the generated labels from the window. I got it working that it expands the window.
from cProfile import label
from pickle import FRAME
import random
import tkinter as tk
from tkinter import BOTH, DISABLED, LEFT, RIGHT, VERTICAL, Y, Frame, Label, filedialog, Text
import os
from tkinter import ttk
from tkinter.font import NORMAL
from tkinter.messagebox import YES
root = tk.Tk()
root.title('guesser')
#Pelin arvonta ohjelma !
def delete():
for child in root.children.values():
info = child.grid_info()
if info['column'] == 0:
child.grid_forget()
def arvonta():
global label
list1 = []
lista = ["Valorant","Rainbow","Vampire: The masquerade","Playerunknown's battlegrounds","Fortnite","Left 4 Dead 2","Counter strike Global offensive","Realm roayale","Black ops 1 zombies/multiplayer","Black ops 2 zombies/multiplayer","Black ops 3 zombies/multiplayer"]
numero = random.randint(0, 10)
hahmo = (lista[numero])
list1.append(hahmo)
for app in list1:
label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
label.pack()
def valorant():
list2 = []
lista2 = ["Brimstone","Viper","Omen","Killjoy","Cypher","Sova","Sage","phoenix","Jett","Reyna","Raze","Raze","Breach","Skye","Yoru","Astra","Kay/o","Chamber","Neon","Fade"]
numero = random.randint(0, 19)
randomValorantagent=(lista2[numero])
list2.append(randomValorantagent)
for app in list2:
label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
label.pack()
def quitter():
quit()
canvas = tk.Canvas(root,height=700,width=700,bg="#263D42")
canvas.pack(side=LEFT,fill=BOTH,expand=1)
frame = tk.Frame(root,bg="green")
frame.place(relwidth=0.8,relheight=0.8,relx=0.1,rely=0.1)
frame.pack(fill=BOTH,expand=1)
my_scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
# Configure The Canvas
canvas.configure(yscrollcommand=my_scrollbar.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion = canvas.bbox("all")))
# Create ANOTHER Frame INSIDE the Canvas
second_frame = Frame(canvas)
# Add that New frame To a Window In The Canvas
canvas.create_window((0,0), window=second_frame, anchor="nw")
#rlls the game
openfile = tk.Button(second_frame,text="Roll a game",padx=10,pady=5,fg="white",bg="#263D42", command=arvonta)
openfile.pack()
#rolls a valorant agent
valorantA = tk.Button(second_frame,text='Roll valorant agent',padx=10,pady=5,fg="white",bg="#263D42",command=valorant)
valorantA.pack()
# stops program
stop = tk.Button(second_frame,text="Quit",padx=10,pady=5,fg="white",bg="#263D42",command=quitter)
stop.pack()
# deletes all info from screen.
deletor = tk.Button(second_frame,text="delete info",padx=10,pady=5,fg="white",bg="#263D42",command=delete)
deletor.pack()
root.mainloop()```
The following does most of what you want. I wrote it some time ago to test Scrollbars because they are wonky IMHO
from tkinter import *
from functools import partial
class ButtonsTest:
def __init__(self):
self.top = Tk()
self.top.title("Click a button to remove")
self.top.geometry("425x200+50+50")
Label(self.top, text=" Click a button to remove it ",
bg="lightyellow", font=('DejaVuSansMono', 12)
).grid(row=0, sticky="nsew")
Button(self.top, text='Exit', bg="orange", width=9,
command=self.top.quit).grid(row=1,column=0,
sticky="nsew")
self.add_scrollbar()
self.button_dic = {}
self.buttons()
self.top.mainloop()
##-------------------------------------------------------------------
def add_scrollbar(self):
self.canv = Canvas(self.top, relief=SUNKEN)
self.canv.config(width=400, height=200)
self.top_frame = Frame(self.canv, height=100)
##---------- scrollregion has to be larger than canvas size
## otherwise it just stays in the visible canvas
self.canv.config(scrollregion=(0,0, 400, 500))
self.canv.config(highlightthickness=0)
ybar = Scrollbar(self.top, width=15, troughcolor="lightblue")
ybar.config(command=self.canv.yview)
## connect the two widgets together
self.canv.config(yscrollcommand=ybar.set)
ybar.grid(row=3, column=2, sticky="ns")
self.canv.grid(row=3, column=0)
self.canv.create_window(1,0, anchor=NW,
window=self.top_frame)
##-------------------------------------------------------------------
def buttons(self):
b_row=1
b_col=0
for but_num in range(1, 51):
## create a button and send the button's number to
## self.cb_handler when the button is pressed
b = Button(self.top_frame, text = str(but_num), width=5,
command=partial(self.cb_handler, but_num))
b.grid(row=b_row, column=b_col)
## dictionary key=button number --> button instance
self.button_dic[but_num] = b
b_col += 1
if b_col > 4:
b_col = 0
b_row += 1
##----------------------------------------------------------------
def cb_handler( self, cb_number ):
print("\ncb_handler", cb_number)
self.button_dic[cb_number].grid_forget()
##===================================================================
BT=ButtonsTest()
in this code i try to add two frames one on the left and second on the right and i need to make the left frame fixed and add scrollbar on the right frame
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
win_width = 1200
win_hight = 720
root=Tk()
root.geometry("{}x{}".format(str(win_width),str(win_hight)))
frame_style = Style()
frame_style.configure('blue.TFrame', background='#1d96f4',highlightthickness=0)
frame_style.configure('white.TFrame', background='#FFFFFF',highlightthickness=0)
frame1 = ttk.Frame(root, style='blue.TFrame')
frame1.grid(row=0,column=0)
frame1.config(width=win_width*(50/100.0),height=win_hight, relief=RIDGE)
frame1.grid_propagate(0)
frame2 = ttk.Frame(root, style='white.TFrame')
frame2.grid(row=0,column=2)
frame2.config(width=win_width*(50/100.0),height=win_hight, relief=RIDGE)
frame2.grid_propagate(0)
my_canvas = Canvas(frame2, background="white",width=1100,height=720)
my_canvas.pack(side=LEFT,fill=Y)
my_scrollbar = ttk.Scrollbar(frame2, orient=VERTICAL , command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))
second_frame = Frame(my_canvas)
my_canvas.create_window((1200,720), window=second_frame)
for i in range(0,50):
title_label = Label(second_frame, text="Test",background='#1d96f4',foreground="#FFFFFF",font=('Helvetica', 22, 'bold'))
title_label.place(x=20, y=40*i)
root.mainloop()
I have tried various methods but have not been able to set the look properly and I don't want to use "pack" at least inside the right frame
So yeah, I just want a scrollbars cause I have a lot of frames, but I just don't get how to use it.
I tried a couple of things with a little variation each time but even though I think I'm getting close it's still not there.
In my code I have a canvas that fills the main Tk window and inside that canvas I have a lot of frames in a grid generated with a for loop.
Code:
import tkinter as to
import tkinter.ttk
def generateFrames(root, o):
pieFrame = Frame(root)
pieFrame.grid(row=int(o/4), column=o%4, padx=25)
mainWindow = tk.Tk()
scrollbar = Scrollbar(mainWindow, orient='vertical')
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
canvas = Canvas(mainWindow, yscrollcommand=scrollbar.set)
scrollbar.config(command=canvas.yview)
canvas.pack(expand=tk.YES, fill=tk.BOTH)
for I in range(16):
generateFrames(canvas, i)
mainWindow.mainloop()
working code is:
import tkinter as tk
import tkinter.ttk
def generateFrames(root, o):
pieFrame = Frame(root)
pieFrame.grid(row=int(o/4), column=o%4, padx=25)
mainWindow = tk.Tk()
scrollbar = Scrollbar(mainWindow, orient='vertical')
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
canvas = Canvas(mainWindow, yscrollcommand=scrollbar.set)
scrollbar.config(command=canvas.yview)
canvas.pack(expand=tk.YES, fill=tk.BOTH)
canvas.configure(scrollregion=(0,0,0,2000))
mainFrame = Frame(mainWindow)
mainFrame.pack(fill=tk.BOTH)
for I in range(16):
generateFrames(mainFrame, i)
canvas.create_window(950, 750, window=mainFrame)
mainWindow.mainloop()
from tkinter import *
import tkinter as tk
import random
f = 0
def test_print():
f = random.randint(0,118)
master.update_idletasks()
# creating Tk window
master = Tk()
master.minsize(600,400)
var = IntVar()
var.set(f)
# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !",
background = "red", fg = "white", command = test_print)
b1.pack(side = TOP, expand = True, fill = BOTH)
label = tk.Label(pane, textvariable = var)
label.pack(side = BOTTOM, expand = False)
# Execute Tkinter
master.mainloop()
This code runs fine but it doesn't give me a random number when i press the button. I need it to give me a random output so i can get a random element from a list. Does anybody have the answer to this?
Here it is. Now you can see that the label changes:
from tkinter import *
import tkinter as tk
import random
def test_print():
f = random.randint(0, 118)
label.configure(text=str(f))
master.update_idletasks()
# creating Tk window
master = Tk()
master.minsize(600, 400)
# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill=BOTH, expand=True)
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text="Click me !",
background="red", fg="white", command=test_print)
b1.pack(side=TOP, expand=True, fill=BOTH)
label = tk.Label(pane)
label.pack(side=BOTTOM, expand=False)
# Execute Tkinter
master.mainloop()
here is the answer
from tkinter import *
import tkinter as tk
import random
maxnumber = 118
f = random.randint(0,maxnumber)
def test_print():
master.update_idletasks()
label.configure(textvariable = var)
# creating Tk window
master = Tk()
master.minsize(600,400)
var = IntVar()
var.set(f)
# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !",
background = "red", fg = "white", command = test_print)
b1.pack(side = TOP, expand = True, fill = BOTH)
label = tk.Label(pane)
label.pack(side = BOTTOM, expand = False)
# Execute Tkinter
master.mainloop()
This question concerns Python's Tkinter.
I first produced this GUI, a simple two-column set of rows in a Labelframe, with an icon on the right:
The above behaviour was correct and expected, based on this following code:
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
root = tk.Tk()
icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
icon_col = tk.PhotoImage(file=icon_colours_fp)
# icon_col = ImageTk.PhotoImage(Image.open(icon_colours_fp))
tk.Label(root, text="Past").grid(row=0, column=0)
tk.Label(root, text="Today").grid(row=1, column=0)
tk.Label(root, text="Future").grid(row=2, column=0)
_b = ttk.Button(root, image=icon_col)
_b['image'] =icon_col
_b.grid(row=0, column=1)
root.mainloop()
I then re-wrote the code as a class, hoping to produce something similar within a Labelframe:
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
class Options(tk.Frame):
def __init__(self, parent):
super().__init__()
main_labelframe = ttk.LabelFrame(parent, text="Test Labelframe")
main_labelframe.pack(fill=tk.BOTH, expand=1)
frame_1 = tk.Frame(main_labelframe)
frame_1_sep = ttk.Separator(main_labelframe, orient=tk.VERTICAL)
frame_2 = tk.Frame(main_labelframe)
frame_1.pack(side=tk.LEFT)
frame_1_sep.pack(side=tk.LEFT, fill=tk.BOTH)
frame_2.pack(side=tk.LEFT)
tk.Label(frame_1, text="Past").grid(row=0, column=0)
tk.Label(frame_1, text="Today").grid(row=1)
tk.Label(frame_1, text="Future").grid(row=2)
icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
icon_col = tk.PhotoImage(file=icon_colours_fp)
_b = ttk.Button(frame_2, image=icon_col)
_b['image'] = icon_col
_b.grid(row=0, column=0)
class Gui(tk.Tk):
def __init__(self):
super().__init__()
options = Options(self)
options.pack()
gui = Gui()
gui.mainloop()
The code then failed, in two respects:
The icon fails to appear.
The ttk Button becomes misaligned. (It appears in the centre, whereas by the grid, it should appear at the top.)
The failed code appears as follows:
I have experimented: among others, I changed the geometry manager to .pack(), and changed the parent of ttk.Button, but without success. Would appreciate some pointers as to where I've gone wrong, especially as to the disappearing icon.
You didn't keep a reference to the image. Easiest way here is to change:
icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=icon_col)
_b['image'] = icon_col
To:
self.icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=self.icon_col)