首页 > 解决方案 > 将单选按钮与 tkinter 中的功能联系起来

问题描述

正如您在此代码中看到的那样,根据单选按钮选择运行函数时,我遇到了这个小问题。

目的是根据单选按钮选择定义当我按下计算时要执行的功能。

import tkinter as tk

master = tk.Tk()
tk.Label(master, text='Choose Color :').grid(row=0)


tk.Label(master, text='What Is The Number ? ').grid(row=2)
fdose = tk.Spinbox(master, from_ = 0, to = 60).grid(row=2, column=1)

def calculate():
    #this should take my input from the spinbox and add 10 to it if I choose Yellow
    #this should take my input from the spinbox and add 100 to it if I choose Green
    pass

v = tk.IntVar()
pen = tk.Radiobutton(master, text = 'Yellow',variable = v, value = 1).grid(row=0, column=1)
pen = tk.Radiobutton(master,text ='Green', variable = v, value = 2).grid(row=1, column=1)


but1 = tk.Button(master, text = 'Close', width = 20, bg = 'black', fg = 'red',activebackground = 'red', activeforeground = 'black', command = master.destroy)
but1.grid(row = 5, column = 1)

but2 = tk.Button(master, text = 'Calculate', width = 20, bg = 'black', fg = 'red',activebackground = 'red', activeforeground = 'black', command = calculate)
but2.grid(row = 5, column = 0)



master.mainloop()

标签: pythontkinter

解决方案


该函数calculate检索在 中选择的值radiobuttons,并调用适当的function.

import tkinter as tk


master = tk.Tk()
tk.Label(master, text='Choose Color :').grid(row=0)


tk.Label(master, text='What Is The Number ? ').grid(row=2)
fdose = tk.Spinbox(master, from_=0, to=60).grid(row=2, column=1)

    
def do_yellow():
    print('doing the yellow thinghy')
    
def do_green():
    print('doing the green thinghy')

def calculate():
    """retrieves the value selected in the radiobuttons, and
    calls the appropriate function.
    """
    [do_yellow, do_green][int(v.get())-1]()

v = tk.IntVar()
pen = tk.Radiobutton(master, text='Yellow', variable=v, value=1)
pen.grid(row=0, column=1)
pen = tk.Radiobutton(master, text='Green', variable=v, value = 2)
pen.grid(row=1, column=1)

but1 = tk.Button(master, text='Close', width=20, bg='black', fg='red', activebackground='red', activeforeground='black', command=master.destroy)
but1.grid(row=5, column=1)

but2 = tk.Button(master, text='Calculate', width=20, bg='black', fg='red', activebackground='red', activeforeground='black', command=calculate)
but2.grid(row=5, column=0)

master.mainloop()

推荐阅读