Python Forum
[Tkinter] how do i add a margin to a Listbox
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] how do i add a margin to a Listbox
#21
Well after finally getting a moment to look at the code and implementing it into my code... for some reason it does not work. It is clearly something I am doing wrong in the initial writing of the code.

Both of the code version works perfectly as they are but when it is put into my original coding it will not display the Listbox widget at al. No error codes are given but it is not seen.
"Often stumped... But never defeated."
Reply
#22
Hi DT2000

So for me it is becoming difficult to understand what is going on at your side. Unfortunately without seeing your complete code piece i can't help you further on. Here i have tested the code successfully with Ubuntu 18.04, Windows 10 and Python 3.5.2

wuf :-)
Reply
#23
DT2000 - It seems as though you are taking the code that wuf wrote, and trying to manipulate it into some other body of code.
The code wuf debugged, is what you said was your complete code.
Therefore, delete what you presented to wuf, and replace it 100 % with wuf's debugged version.
Reply
#24
I uploaded the window_2 part of the code, without the background image because that is where the Listbox is used.

Here is the full code.

window_2 starts at line 54. The Listbox code is at line 332.

import os
##import tkinter
import sqlite3
##import win32print
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#===================================== MAIN ====================================
def main():
#============================= CONNECT TO DATABASE =============================
    conn = sqlite3.connect('Recipe.db')
    c = conn.cursor()
#========================= CREATE DATABASE WITH TABLES =========================
    c.execute('''CREATE TABLE IF NOT EXISTS Recipes(
    Dish_Type CHAR(50),
    Recipe CHAR(50),
    Cook_Time CHAR(15),
    Serves CHAR(8),
    Ingredients CHAR(10000) ,
    Instructions CHAR(10000));''')
    conn.commit()

    c.execute('''CREATE TABLE IF NOT EXISTS Version(
    Welcome Decimal(10));''')
    conn.commit()

    c.execute('''CREATE TABLE IF NOT EXISTS Welcome(
    Welcome TEXT(2500));''')
    conn.commit()
#================================= MAIN WINDOW =================================
    root = tkinter.Tk()
    root.title('Recipes')
    image1 =tkinter.PhotoImage(file='Menu.gif')
    w = 1024
    h = 612
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))
    panel1 =tkinter.Label(root, image=image1)
    panel1.pack(side='top', fill='both', expand='yes')
    panel1.image = image1
    root.wm_iconbitmap('recipe.ico')
    class OpenButton(Widget):
        '''Button widget.'''
        def __init__(self, master=None, cnf={}, **kw):
            start_button = tkinter.Button(root, text='Open',
            font='Times 12 bold italic', border = 2,  bd=5, bg = '#F9F8D6',
            fg = '#9A0615', width = 10, height = 2, overrelief='raised',
            command = window_2)
            start_button.place(x=448, y=461)
#================================== WINDOW 2 ===================================
    def window_2():
        root.destroy()
        window_2 = tkinter.Tk()
        image2 = 'window2.gif'
        bg_image2 = tkinter.PhotoImage(file=image2)
        w = 1024
        h = 612
        ws = window_2.winfo_screenwidth()
        hs = window_2.winfo_screenheight()
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)
        window_2.geometry('%dx%d+%d+%d' % (w, h, x, y))
        panel2 =tkinter.Label(window_2, image=bg_image2)
        panel2.pack(side='top', fill='both', expand='yes')
        panel2.image = bg_image2
        window_2.title('Recipes')
        window_2.resizable(0,0)
        window_2.wm_iconbitmap('recipe.ico')
#============================== GET RECIPE QUERY ===============================
        def getRecipe(event):
            Dish_Type = StringVar()
            Recipe = StringVar()
            Cook_Time = StringVar()
            Serves = StringVar()
#================================== WINDOW 3 ===================================
            def back_page():
                window_2.deiconify()
                window_3.destroy()
            window_3 = tkinter.Toplevel()
            window_3.title('Recipes')
            window_3.resizable(0,0)
            window_3.wm_iconbitmap('recipe.ico')
            w = 1024
            h = 612
            ws = window_3.winfo_screenwidth()
            hs = window_3.winfo_screenheight()
            x = (ws/2) - (w/2)
            y = (hs/2) - (h/2)
            window_3.geometry('%dx%d+%d+%d' % (w, h, x, y))
            image3  = 'window3.gif'
            bg_image3 = tkinter.PhotoImage(file=image3)
            panel3 = Label(window_3, image=bg_image3)
            panel3.pack(side='top', fill='both', expand='yes')
            panel3.image = bg_image3
            window_3.title('Recipes')
            window_3.wm_iconbitmap('recipe.ico')
            window_3.protocol('WM_DELETE_WINDOW', window_3)
#================================= SAVE RECIPE =================================
            def Save():
                window_2.iconify()
                try:
                    saveInput = Recipe.get()
                    c.execute('SELECT Recipe FROM Recipes WHERE Recipe = :saveInput',
                    {'saveInput': saveInput})
                    conn.commit()
                    saveResult = c.fetchone()
                    if saveResult == None:
                        c.execute('''INSERT INTO Recipes VALUES (?,?,?,?,?,?)''',
                        (Dish_Type.get(), (Recipe.get()),
                        (Cook_Time.get()), (Serves.get()), (ingred.get(1.0, END)),
                        (instruct.get(1.0, END))))
                        conn.commit()
                        messagebox.showinfo('Recipes','Recipe saved successfully.')
                        dish_type_entry.delete(0, END)
                        recipe_entry.delete(0,END)
                        cook_time_entry.delete(0,END)
                        serves_entry.delete(0,END)
                        ingred.delete(1.0,END)
                        instruct.delete(1.0,END)
                    else:
                        messagebox.showinfo('Recipes',
                        'That recipe name already exists in the database.')
                except:
                    messagebox.showerror('Recipes','Database Error.')
#================================ CLOSE PROGRAM ================================
            def exit():
                window_2.destroy()
#================================ DELETE RECIPE ================================
            def delete():
                    try:
                        checkInput = Recipe.get()
                        c.execute('SELECT Recipe FROM Recipes WHERE Recipe = :checkInput',
                        {'checkInput': checkInput})
                        conn.commit()
                        theResult = c.fetchone()
                        if theResult == None:
                            messagebox.showinfo('Recipes',
                            'That recipe name does not exist in the database.')
                            recipe_entry.delete(0,END)
                        else:
                            MsgBox =  messagebox.askyesno('Recipes',
                            'Are you sure you want to delete this recipe?',
                            icon = 'warning')
                            if MsgBox == True:
                                messagebox.showinfo('Recipes',
                                'The recipe will now be delete.')
                                c.execute('DELETE FROM Recipes WHERE Recipe =:checkInput',
                                {'checkInput': checkInput})
                                conn.commit()
                                messagebox.showinfo('Recipes',
                                'The recipe has been deleted successfully.')
                                recipe_entry.delete(0,END)
                            else:
                                messagebox.showinfo('Recipes',
                                'Delete has been cancelled.')
                                recipe_entry.delete(0,END)
                    except:
                        messagebox.showerror('Recipes','Database Error.')
#================================ TAB KEY FOCUS ================================
            def focus_next_window(event):
                event.widget.tk_focusNext().focus()
                return("break")
#=============================== FRAME 3 WIDGETS ===============================
            window_2.iconify()
            dish_type = tkinter.Label(window_3, font=('Times 9 bold'),
            text='Category:', bg = '#FFD599', fg = '#9A0615')
            dish_type.place(x=210, y=125)
            dish_type_entry = tkinter.Entry(window_3, textvariable=Dish_Type,
            width = 30, bg = '#FFD599', fg = '#9A0615', justify=CENTER)
            dish_type_entry.place(x=275, y=126)
            dish_type_entry.focus()
            recipe = tkinter.Label(window_3, font=('Times 9 bold'),
            text='Recipe:', bg = '#FFD599', fg = '#9A0615')
            recipe.place(x=210, y=145)
            recipe_entry = tkinter.Entry(window_3, textvariable=Recipe,
            width = 30, bg = '#FFD599', fg = '#9A0615', justify=CENTER)
            recipe_entry.place(x=275, y=146)
            serves = tkinter.Label(window_3, font=('Times 9 bold'),
            text='Serves:', bg = '#FFD599', fg = '#9A0615')
            serves.place(x=547, y=125)
            serves_entry = tkinter.Entry(window_3, textvariable=Serves,
            width = 8, bg = '#FFD599', fg = '#9A0615', justify=CENTER)
            serves_entry.place(x=623, y=126)
            cook_time = tkinter.Label(window_3, font=('Times 9 bold'),
            text='Cook Time:', bg = '#FFD599', fg = '#9A0615')
            cook_time.place(x=547, y=145)
            cook_time_entry = tkinter.Entry(window_3, textvariable=Cook_Time,
            width = 12, bg = '#FFD599', fg = '#9A0615', justify=CENTER)
            cook_time_entry.place(x=623, y=146)
            ingred = tkinter.Text(window_3, font=('Times 10'), height = 20,
            width=40, bd=1, bg = '#FFD599', fg = '#9A0615',padx=5, pady=5)
            ingred.place(x=210, y=195)
            ingred.bind("<Tab>", focus_next_window)
            yscroll3 = tkinter.Scrollbar(window_3, command=ingred.yview,
            orient=tkinter.VERTICAL)
            yscroll3.place(x=461, y=195)
            ingred.configure(yscrollcommand=yscroll3.set)
            instruct = tkinter.Text(window_3, font=('Times 10'), height = 20,
            width=40, bd=1, bg = '#FFD599', fg = '#9A0615',padx=5, pady=5)
            instruct.place(x=547, y=195)
            yscroll4 = tkinter.Scrollbar(window_3, command=instruct.yview,
            orient=tkinter.VERTICAL)
            yscroll4.place(x=798, y=195)
            instruct.configure(yscrollcommand=yscroll4.set)
            saveButton = tkinter.Button(window_3, text='Save a Recipe',
            font='Times 9 bold italic', border = 1, height = 1, width = 11,
            bd=4, bg = '#F9F8D6', fg = '#9A0615', command = Save)
            saveButton.place(x=215, y=514)
            deleteButton = tkinter.Button(window_3, text='Delete a Recipe',
            font='Times 9 bold italic', border = 1, height = 1, width = 11,
            bd=4, bg = '#F9F8D6', fg = '#9A0615', command = delete)
            deleteButton.place(x=337, y=514)
            printButton = tkinter.Button(window_3, text='Print Recipe',
            font='Times 9 bold italic', border = 1, height = 1, width = 11,
            bd=4, bg = '#F9F8D6', fg = '#9A0615', command = printer)
            printButton.place(x=459, y=514)
            backButton = tkinter.Button(window_3, text='Back a Page',
            font='Times 9 bold italic', border = 1, height = 1, width = 11,
            bd=4, bg = '#F9F8D6', fg = '#9A0615', command = back_page)
            backButton.place(x=581, y=514)
            exitButton = tkinter.Button(window_3, text='Exit Program',
            font='Times 9 bold italic', border = 1, height = 1, width = 11,
            bd=4, bg = '#F9F8D6', fg = '#9A0615', command = exit)
            exitButton.place(x=703, y=514)
            try:
                dish_type_entry.delete(0,END)
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Dish_Type FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                dish_type_result = c.fetchone()
                dish_type_entry.insert(0,dish_type_result[0])
                recipe_entry.delete(0,END)
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Recipe FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                recipe_result = c.fetchone()
                recipe_entry.insert(0,recipe_result[0])
                serves_entry.delete(0,END)
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Serves FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                serves_result = c.fetchone()
                serves_entry.insert(0,serves_result[0])
                cook_time_entry.delete(0,END)
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Cook_Time FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                cook_time_result = c.fetchone()
                cook_time_entry.insert(0,cook_time_result[0])
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Ingredients FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                ingredients_result = c.fetchone()
                ingred.insert(1.0,ingredients_result[0])
                ingred.config(wrap=WORD)
                index = output.curselection()
                selected = output.get(index)
                c.execute('SELECT Instructions FROM Recipes WHERE Recipe = :selected',
                {'selected': selected})
                instructions_result = c.fetchone()
                instruct.insert(1.0, instructions_result[0])
                instruct.config(wrap=WORD)
            except:
                pass
##                messagebox.showerror('DataBase Error', 'Failed to load category')
#=========================== MODULE 2 CLEAR INPUT ==============================
        def clear1():
            output.delete(0,END)
#================================ SELECT QUERY =================================
        def select():
            try:
                output.delete(0, END)
                selection = var.get()
                c.execute('SELECT Recipe FROM Recipes WHERE Dish_Type = :selection',
                {'selection': selection})
                results = c.fetchall()
                for recipe, in results:
                    output.insert(0,recipe)
            except:
                messagebox.showerror('Recipes', 'Failed to load category')
#================================ OPTION MENU ==================================
        var = tkinter.StringVar(window_2)
        var.set('Category')
        choices = [
            'Appetizers',
            'Beef',
            'Beverages',
            'Bakery',
            'Desserts',
            'Eggs',
            'Lamb',
            'Pasta',
            'Pork',
            'Potato',
            'Poultry',
            'Rice',
            'Salads',
            'Sandwiches',
            'Sauces/Dips',
            'Sea Food',
            'Slow Cooker',
            'Soups/Chili',
            'Stews',
            'Sushi',
            'Vegetables',
            'Vegetarian',
            'Wild Game']
        option = tkinter.OptionMenu(window_2, var, *choices)
        option.config(font=('Times 9 bold'), bg = '#F9F8D6', fg = '#9A0615')
        option.place(x=210, y=136)
        option['menu'].config(bg = '#F9F8D6', fg = '#9A0615')
        backer = tkinter.Label(window_2, font=('Times 16 bold'),
        text='                 ')
        backer.place(x=360, y=137)
        button = tkinter.Button(window_2, text='Load Category',
        font=('Times 9 bold'), bg = '#F9F8D6', fg = '#9A0615', command=select)
        button.place(x=362, y=139)
#=================================== WINDGETS ==================================
        output = tkinter.Listbox(window_2, font=('Times 10'), height = 20,
        width=42, bd=1, bg = '#FFD599', fg = '#9A0615', selectmode=SINGLE)
        output.place(x=210, y=195)
        yscroll1 = tkinter.Scrollbar(command=output.yview,
        orient=tkinter.VERTICAL)
        yscroll1.place(x=463, y=196)
        output.configure(yscrollcommand=yscroll1.set)
        output.bind('<ButtonRelease-1>', getRecipe)
        instructions = tkinter.Text(window_2, font=('Times 10'), height = 21,
        width=42, bd=1, bg = '#FFD599', fg = '#9A0615',padx=5, pady=5)
        instructions.place(x=547, y=195)
        yscroll2 = tkinter.Scrollbar(command=instructions.yview,
        orient=tkinter.VERTICAL)
        yscroll2.place(x=810, y=196)
        instructions.configure(yscrollcommand=yscroll2.set)
        enterButton = tkinter.Button(window_2, text='Enter a Recipe',
        font='Times 9 bold italic', border = 1, height = 1, width = 12, bd=3,
        bg = '#F9F8D6', fg = '#9A0615')
        enterButton.place(x=293, y=525)
        enterButton.bind('<Button-1>', getRecipe)
        clear1Button = tkinter.Button(window_2, text='Clear Page',
        font='Times 9 bold italic', border = 1, height = 1, width = 12, bd=3,
        bg = '#F9F8D6', fg = '#9A0615', command = clear1)
        clear1Button.place(x=630, y=525)
#================================ WELCOME PANE =================================
        c.execute('SELECT * FROM Welcome WHERE welcome = Welcome')
        welcome_result2 = c.fetchall()
        for welcome_result in welcome_result2:
            instructions.insert(1.0,welcome_result[0])
            instructions.config(wrap=WORD, state=DISABLED)

    OpenButton()
    root.mainloop()
if __name__ == '__main__':
    main()
"Often stumped... But never defeated."
Reply
#25
Hi DT2000

Thanks for showing your extended app script. As i see you are using mainly the place layout structure. Thats the reason why you could not implement my recommended 'listbox' proposal. For me its also very difficult to integrate my recomondations in your existing script as it is. I would have to modify your whole script. Unfortunaly i have no time for this. Wishing you good luck for the further development of your application.

wuf :-)
Reply
#26
Being new to python I am still learning the best ways to write. I appreciate the time taken to look things over.
For now I will live with the lack of padding inside the Listbox, at least until I am more familiar with proper layout techniques so I can rewrite the code.

Thank you, to you and Larz for all the advice and help it is greatly appreciated.

73s
"Often stumped... But never defeated."
Reply
#27
Quote:73s
Amateur radio I presume. I am a ham, won't expose call sign here though.
good luck going forward.
Reply
#28
Larx60+... Amateur indeed. Being in an apartment since relocating I have not been able to setup a rig but will hopefully soon.
"Often stumped... But never defeated."
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Text Button - How Do I Reduce The Margin? vman44 6 11,029 Apr-27-2020, 10:48 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020