#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2017
    Posts
    20
    Rep Power
    0

    [Python 3 + Tkinter] Checkbutton not show


    Hey Python Programmers...

    I try to create an checkbox they can convert the image to 'RGB' or to 'L'... but
    this checkbutton is not showing... this is my code:

    f
    Code:
    rom tkinter import *
    from tkinter import ttk
    from tkinter.filedialog import askopenfilename
    from PIL import Image, ImageTk
    
    
    
    main = Tk()
    main.geometry("150x250+300+300")
    
    def Open():
        temp = askopenfilename(parent = main, initialdir = 'C:/', filetypes = [('PNG File: ', '*.png')], title = 'Open Image')
    
        try:
            with open(temp) as filename:
                img = Image.open(temp)
                photo = ImageTk.PhotoImage(img)
                show = Label(main, image = photo)
                show.image = photo
                show.pack(padx = 10, pady = 10, side = RIGHT)
                show.geometry("20x20")
    
                var = IntVar()
                c = Checkbutton(main, text = 'Image Mode', variable = var, onvalue = img.convert('RGB'), offvalue = img.convert('L')).grid(row=0, sticky=W)
                c.pack(side = side, anchor = anchor, expand = YES)
                
        except:
            print('Image Not Exit')
    
    
    
    menu = Menu(main)
    main.config(menu=menu)
    
    filemenu = Menu(menu, tearoff = 0)
    filemenu.add_command(label = 'Open', command = Open)
    menu.add_cascade(label = 'File', menu = filemenu)
        
    main.mainloop()

    Can you help me to correct my code, just i can expiriment with it ?...
    Thanks for help, Jamie.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    656
    Rep Power
    39
    All variables created in a function are local to that function, i.e are garbage collected when the function exits. So img, photo, var, etc. do not exist outside of the function, which is one of the reasons it is emphasized that classes should be used. Will do my best to come up with modified code later today. Also note that "c" (from Checkbutton) is None as the last function called on the line is grid() and grid() returns None. You then pack() "c" which will produce and error as you can not use both. To keep the Tkinter ID in "c" use 2 lines
    Code:
                ## returns Checkbutton instance instead of None
                c = Checkbutton(main, text = 'Image Mode', variable = var, onvalue = img.convert('RGB'), offvalue = img.convert('L'))
                c.grid(row=0, sticky=W)
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    656
    Rep Power
    39
    This program shows how to use Checkbuttons to change an image using class instance objects which are not garbage collected when the function exits. You can include whatever you want in the callback function. This program changes the image to show that it is working.
    Code:
    from tkinter import *
    
    class ChangeImage():
        def __init__(self, main):
            ## instance objects (self.), can be used throughout
            ## the class
            self.main=main
            self.photos=[]  ## save photos in memory
            self.checkbutton_vars=[]  ## use IntVars in other function
    
            self.load_images()
            self.create_checkbuttons()
    
            self.show = Label(self.main, image = self.photos[0])
            self.show.grid(row=1, column=1)
    
            Button(main, text="Quit", width=10, bg="orange",
                   command=self.main.quit).grid(row=10, column=1)
    
        def cb_checked(self):
            """ this function is called when a chectbutton is checked/unchecked
            """"
            for ctr in range(len(self.checkbutton_vars)):
                if self.checkbutton_vars[ctr].get():     ## IntVar not zero==checked
                    print('%d is checked' % (ctr))
                    ## change image
                    self.show['image']=self.photos[ctr]
                    ## take the first box checked only
                    return
    
            def create_checkbuttons(self):
                """ create 3 Checkbuttons, one for each image, and store the
                    variable for each Checkbutton's IntVar in a list for use in the
                    callback command function
                """
                for ctr in range(3):
                    var = IntVar()
                    c = Checkbutton(main, text = 'Image # %d' % (ctr+1),
                                    variable = var, command=self.cb_checked)
                    c.grid(row=ctr+2, column=1, sticky='w')
    
                    ## save this checkbuttons's IntVar
                    self.checkbutton_vars.append(var)
    
            def load_images(self):
                """ load 3 images into a list so we don't have to 
                    reload them every time they are to be displayed
    
                    Images are hard coded into the program instead of
                    loading from a file
                """
                ladybug_gif_b64='''\
    R0lGODlhIAAgALMAAP///wAAADAwMP99Hf8AAP+lAP//AMopUwAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAACH5BAAAAAAALAAAAAAgACAAAwTHEMhJq714hp3lDh0GiqH2UWOVAt96pUIsBLKglWg87Dwv
    4xMBj0Asxgg+XKxwLBJrxUGsI5TKnARoVHoLDp5XbNP5cwmNAqwa/aOc13ByrfKOw2UGw1SSxrb+
    AWIxeXsAaX92UDQ1Nh6BdneMhQIHkHGSjYaVlmt4epmacp19YAKEoJRspKWrjBapWWGqcm1uB5tj
    ok4HZa+3m5wEt5kuhpTAcb+FVL/NzspAfDHPysslMJjEIS0oLygnOMVd0SwcHeDk6errEQA7
    '''
    
                grape_gif='''\
    R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
    /////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
    0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
    YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
    NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
    '''
                house='''R0lGODdhFQAVAPMAAAQ2PESapISCBASCBMTCxPxmNCQiJJya/ISChGRmzPz+/PxmzDQyZDQyZDQy
    ZDQyZCwAAAAAFQAVAAAElJDISau9Vh2WMD0gqHHelJwnsXVloqDd2hrMm8pYYiSHYfMMRm53ULlQ
    HGFFx1MZCciUiVOsPmEkKNVp3UBhJ4Ohy1UxerSgJGZMMBbcBACQlVhRiHvaUsXHgywTdycLdxyB
    gm1vcTyIZW4MeU6NgQEBXEGRcQcIlwQIAwEHoioCAgWmCZ0Iq5+hA6wIpqislgGhthEAOw==
    '''
                for photo in (ladybug_gif_b64, grape_gif, house):
                    self.photos.append(PhotoImage(data=photo))
     
    ##---------------------------------------------------------------
    main = Tk()
    CI=ChangeImage(main)
    main.mainloop()
    Last edited by dwblas; January 4th, 2018 at 11:46 PM.

IMN logo majestic logo threadwatch logo seochat tools logo