python - 将单选按钮与 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()
解决方案
该函数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()
推荐阅读
- javascript - 如何在不更改当前 HTML 结构的情况下使用 css 在顶部元素上方对齐底部元素(而不是覆盖)
- python - python 3范围和输入?
- node.js - Heroku 部署不适用于 postgresql api
- verilog - 意外的高阻抗输出
- ios - 在 Swift UI 中使用对角线分割矩形视图
- javascript - 列表由于某种原因不清楚,即使它写得正确
- mysql - 将utc字符串转换为日期SQL
- c# - 二进制文件读写
- qt - QBtyeArray QDataStream qCompress 到文件添加额外的前导字节
- r - 在 R Leaflet 中实现 groupedLayerControl 插件的问题