Problem with variables and Tkinter...

Peter Otten __peter__ at web.de
Tue Oct 14 07:01:09 EDT 2003


Baltor wrote:

> OK, so I'v got 11 radio buttons hooked up to one variable:
> self.weaponbonus. However, no matter what radio button I have checked,
> self.weaponbonus is treated as 0. This is my code:
[...] 
> Does anyone know what's wrong?

The random button must trigger a function that sets the IntVar. One way to
achieve this is presented below. I would prefer a normal Button over a
Radiobutton to set the random value.


<code>
import Tkinter as tk
import random

class BonusFrame(tk.Frame):
    def __init__(self, *args, **kwd):
        tk.Frame.__init__(self, *args, **kwd)
        self.grid()
        self.weaponbonus = tk.IntVar()
        for i in range(10):
            val = i + 1
            btn = self.radio1 = tk.Radiobutton(self, text="+%d" % val,
            variable=self.weaponbonus, value=val)
            btn.grid(row=i//5, column=i%5)

        def setRandom():
            self.weaponbonus.set(random.randint(1, 10))

        if 0: #not recommended
            self.radioran = tk.Radiobutton(self, text="Random",
            variable=self.weaponbonus, value=99, command=setRandom)
            self.radioran.grid(row=3, column=0, columnspan=5)
        else:
            self.radioran = tk.Button(self, text="Random",
            command=setRandom)
            self.radioran.grid(row=3, column=0, columnspan=5)

        # for your information only
        lbl = tk.Label(self, text="Bonus is")
        lbl.grid(row=4, column=0, columnspan=2)
        lbl = tk.Label(self, textvariable=self.weaponbonus)
        lbl.grid(row=4, column=1)

root = tk.Tk()
frame = BonusFrame(root)
root.mainloop()
</code>

Peter




More information about the Python-list mailing list