getting the label value of a button in Gtk - python

Am learning Gtk. I wanted to build a calculator, in which i want to display the number pressed , in the textbox. I have completed it, by calling different functions for different buttons clicked, and appending the value in the textbox with the value of the button pressed. Using python 2.7.3
Is there a way to obtain the label value of the button pressed so that i can use a single function instead of 10 functions from 0 to 9?
Thanks in advance

Button callbacks include the widget itself, and you can also pass data. See here.

instead of reading the label of the GtkButton, which is pretty much error prone, you should associate the value represented by the button to the button instance itself, e.g.:
button = Gtk.Button(label='1')
button._value = 1
# add button to the container
button.connect('clicked', on_button_clicked)
button = Gtk.Button(label='2')
button._value = 2
# add button to the container
button.connect('clicked', on_button_clicked)
and then read the value from the button instance inside the signal handler, e.g.:
def on_button_clicked(button):
print 'you pressed the button of value: %d' % (button._value)
GtkWidget instances in Python are Python object, and thus behave like any other Python object.

Related

Not able to access list in another window in tkinter python

from tkinter import *
root=Tk()
root.title("")
#root.geometry("500x500")
global c
c=[]
def new():
win=Toplevel()
win.title("")
for i in range(0,25):
name=Label(win,text=str(c[i]),bg='#ADD8E6',fg='white',width=20)
name.grid(column=1,row=i)
for i in range(1,26):
name=Label(root,text='enter name of team'+str(i),bg='#ADD8E6',fg='white',width=20)
name.grid(column=1,row=i)
entry=Entry(root,bg='white',fg='black')
entry.grid(column=2,row=i)
c.append(entry.get())
submit=Button(root,text='Submit',bg='red',fg='white',command=new)
submit.grid(column=1,row=26,columnspan=3)
root.mainloop()
after taking the input form different boxes in the first window , it does not put the same name in the 2nd window when required. It just sends a window whith the speciifed bgcolour
PLaese HElp
The reason why you are not getting the right values is that when the program is run the Entry widgets are empty by default so the list is getting no values and when the button is pressed, it. displays labels text = "" on the second window.
To fix this, get the values of Entry widgets dynamically means get the values when the button is pressed. You can store each Entry widget into a list and later access them in the new function.
In your code, you just need to change two lines.
Change c.append(entry.get()) with c.append(entry).
In the new function change the argument value of "text" of label name from text=str(c[i]) to text=str(c[i].get()).

Python Gtk3, How can I insert a Response (Button) to MessageDialog?

some times I need to insert new response (button) to MessageDialog but I don't know how I can do this. for example msg_dialog.insert_response(Gtk.STOCK_OK, Gtk.ResponseType.OK, 2)
Thanks
The method you are looking for is Gtk.Dialog.add_button:
Adds a button with the given text and sets things up so that clicking
the button will emit the Gtk.Dialog ::response signal with the given
response_id. The button is appended to the end of the dialog’s action
area. The button widget is returned, but usually you don’t need it.
If you want to add several buttons, then you can use Gtk.Dialog.add_buttons:
The add_buttons() method adds several buttons to the Gtk.Dialog using
the button data passed as arguments to the method. This method is the
same as calling the Gtk.Dialog.add_button() repeatedly.
The button data pairs - button text (or stock ID) and a response ID integer are passed individually. For example:
dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)
will add “Open” and “Close” buttons to dialog.

Python: Button widget in Tkinter

I have just now begun with GUI programming in Python 2.7 with Tkinter.
I want to have a button Browse, which when clicked opens the Windows File Explorer and returns the path of file selected to a variable. I wish to use that path later.
I am following the code given here. It outputs a window displaying 5 buttons, but the buttons do nothing. On clicking the first button, it doesn't open the selected file.
Likewise, on clicking the second button, the askopenfilename(self) function is called and it should return a filename. Like I mentioned, I need that filename later.
How to I get the value returned by the function into some variable for future use?
There is no point in using return inside a callback to a button. It won't return to anywhere. The way to make a callback save data is to store it in a global variable, or an instance variable if you use classes.
def fetchpath():
global filename
filename = tkFileDialog.askopenfilename(initialdir = 'E:')
FWIW (and unrelated to the question): you're making a very common mistake. In python, when you do foo=bar().baz(), foo takes the value in baz(). Thus, when you do this:
button = Button(...).pack()
button will take the value of pack() which always returns None. You should separate widget creation from widget layout if you expect to save an actual reference to the widget being created. Even if you're not, it's a good practice to separate the two.

More on passing arguments to tkinter button command

I have a number of test files in a single directory. I'm trying to write a GUI to allow me to select and run one of them.
So, I have a loop that scans the directory and creates buttons:
for fnm in glob.glob ('Run*.py'):
tstName = fnm[3:-3] # Discard fixed part of filename
btn = Button (self, text=tstName,
command=lambda: self.test(tstName))
btn.grid (row=rowNum, column=0, pady=2)
rowNum += 1
This creates my GUI correctly, with buttons labelled say, A and B but when I press on the button labelled A it passes B to the test method.
I've looked around and found this question How can I pass arguments to Tkinter button's callback command? but the answer doesn't go on to use the same variable name, with a different value, to configure another widget. (In fact, by tying the variable name to the widget name it almost implies that the technique won't work in this case, as I've found.)
I'm very new to Python, but am quite familiar with creating this kind of GUI using Tcl/TK and I recognise this problem - the value of tstName is being passed when I press the button, but I want it to pass the value the variable had when I created it. I know how I'd fix that in Tcl/Tk - I'd define a command string using [list] at creation time which would capture the value of the variable.
How do I do the same in Python?
You need to bind the current value of tstName at the time you define the button. The way you're doing it, the value of tstName will whatever it is at the time you press the button.
To bind the value at the time that you create the button, use the value of tstName as the default value of a keyword parameter to the lambda, like so:
btn = Button(..., command=lambda t=tstName: self.test(t))

Python Tkinter: Changing other button's text from event handler of one button

I have the following problem when using tkinter to create a very simple window containing a matrix of buttons: When one of the buttons is clicked, the event handler changes the text of that button using the configure method on the button widget. This works. But I also want to change the text in one of the other buttons, which does not work. The method I use is that on creating the button, I store the object returned by the Button method before I use the grid geometry manager to place it. This object looks like ".123456789L" when printed and seems to be a pointer to the widget. I also use configure on this to change the button text. But somehow it seems to be wrong, because it works sometimes, and most of the times not. There's unfortunately no error message, just nothing happens when calling configure. I checked and it seems to be the correct pointer to the widget. Do I have to use a special way to affect a widget other that the one that called the event handler? These are the relevant parts of the code:
# CREATING THE BUTTONS:
buttons={} # global
for i in range(3):
for j in range(3):
button = Tkinter.Button(self,text='foo')
buttons[button]=(i,j)
button.grid(column=j,row=i)
button.bind( "<Button-1>", self.OnButtonClick )
# CHANGING BUTTONS:
def find_button(i,j):
"""Return the pointer to the other button to be changed when a button has been clicked."""
for button,key in buttons.items():
if key==(i,j): return button
def OnButtonClick(self,event):
print "You clicked the button",buttons[event.widget]
i,j=buttons[event.widget]
old_button=find_button(i,j) # This is simplified, I don't actually pass i,j, but other values. But I checked this and it returns the reference to the correct button. But this simplified version works the same way, just assume a different button that the one pressed would be returned.
old_button.configure(text = 'blabla') # THIS DOES NOT WORK
event.widget.configure(text = 'something') # THIS WORKS
I have the same problem and i solve it with:
buttons[button]=(i,j,button)
and in the function OnButtonClicK:
i,j,old_button=buttons[event.widget]
old_button.configure(text = 'blabla') # THIS DOES NOT WORK

Categories

Resources