TkPhotoImage (click and change image button)

C

csjasnoch

So I found this simple code for using a button with a picture..

require 'tk'



def doit

puts "Want to change image and set some flags here....\n"
end


class Picture


def initialize(root)
image1 = TkPhotoImage.new { file "light_on.gif" }
image2 = TkPhotoImage.new { file "light_off2.gif" }
b = TkButton.new(root) {
image image1
command proc {self.doit} }
b.bind("Enter") { b.configure('image'=>image2) }
b.bind("Leave") { b.configure('image'=>image1) }
b.pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
end



parent = TkRoot.new{ title 'Pictures' }
Picture.new(parent)
Tk.mainloop

I dont really care about the Enter/Leave imaging. But rather I want it
to change image when it is clicked...

Is there something to pass it (like "Clicked" ) that would bind when it
is clicked?

But ideally I want to be able to check a current status variable and
depending on the variable image becomes one or the other. It is for a
light switch (thus the files are named "light_on" etc).
 
C

csjasnoch

For future reference the line:
command proc {self.doit} }
should be
command proc {doit} }
 
C

csjasnoch

Seems making readers for the button will do it. If anyone has a simpler
way I would like to know.. I will modify this (for my application), but
here it is if anyone else ever needs to know


require 'tk'






class Picture
attr_reader :b, :image1, :image2, :satus
attr_writer :b, :image1, :image2, :status

def doit

puts "Something done....\n"
if(@status) #turn off
@status = false
@b.configure('image' => @image2)
else #turn on
@status = true
@b.configure('image' => @image1)
end
end
def initialize(root)
#init status variable
@status = true
@image1 = TkPhotoImage.new { file "light_on.gif" }
@image2 = TkPhotoImage.new { file "light_off2.gif" }

changeImage = proc{doit}

@b = TkButton.new(root) {
image @image1
command changeImage }
#@b.bind("Enter") { @b.configure('image'=>@image2) } #of course no
need to bind upon entrance and leaving...
#@b.bind("Leave") { @b.configure('image'=>@image1) }
@b.pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
end



parent = TkRoot.new{ title 'Pictures' }
Picture.new(parent)
Tk.mainloop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top