简体   繁体   中英

Tkinter radio buttons always gives values of 0

I'm trying to use radio buttons to define a variable to be used in the rest of my script.

When I run this code, shift is always 0.

I have copied and pasted code from online doing something similar, but the values are always 0.

I am using Spyder to run python3.

Thanks.

from tkinter import *
root = Tk()

def pixelShift():
        shift = var.get()
        print(shift)

var = IntVar()

Radiobutton(root,
            text        = '1 Pixel',
            variable    = var,
            value       = 1,
            command     = pixelShift
            ).pack(anchor = W)

Radiobutton(root,
            text        = '10 Pixels',
            variable    = var,
            value       = 10,
            command     = pixelShift
            ).pack(anchor = W)

Radiobutton(root,
            text        = '100 Pixel',
            variable    = var,
            value       = 100,
            command     = pixelShift
            ).pack(anchor = W)

root.mainloop()

You are creating a new Tk() instance by using

var = IntVar()

You should use

root = Toplevel()

or

var = IntVar(root)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM