Reputation: 31
I am using tkinter as a front end for Cisco IOS automation, but the problem i face is i need to have check-boxes available, if checked the text associated to it should be passed to the Cisco IOS. I tried to look into tkinter documentation but no luck.
Var = Tkinter.StringVar()
cv1 = Tkinter.Checkbutton(SecondFrame,text='show cdp neighbor', variable=Var)
cv1.grid(row=3, column=5, sticky='S', padx=5, pady=2)
Upvotes: 1
Views: 4092
Reputation: 101
if checked the text associated to it should be passed to the Cisco IOS
Indicate that you need to assign a variable with Widget.text
(here Checkbutton.text
).
Widget.text
valueFrom TkDocs:
text: The label displayed next to the checkbutton. Use newlines ('\n') to display multiple lines of text.
To get this property:
Checkbutton.cget()
(see answer above)Checkbutton.text
or Checkbutton["text"]
Here, cv1.text
or cv1["text"]
As using Widget.bind()
to bind click event to Checkbutton
instance is not working on my machine, here I
assign a callback function to Checkbutton.command
and check by Checkbutton.variable
if the button has been checked.
from Tkinter import * # import tkinter if using python3
Var = IntVar(0) # use IntVar to store stat whether the button is checked
# If use StringVar() for variable, set `Checkbutton.onstate` and `Checkbutton.offstate`
# see TkDocs above for details
def callback(): # command callback doesn't needed Event as argument
if Var.get() == 0: # not checked
return # do nothing
global command
command.append(cv1.text)
cv1 = Checkbutton(SecondFrame, text="show cdp neighbor", command=callback)
cv1.grid(row=3, column=5, sticky="S", padx=5, pady=2)
Here variable is not Checkbutton.variable
:
variable: The control variable that tracks the current state of the checkbutton; see Section 52, “Control variables: the values behind the widgets”. Normally this variable is an IntVar, and 0 means cleared and 1 means set, but see the offvalue and onvalue options above.
related questions:
Upvotes: 0
Reputation: 4730
This is actually pretty simple:
from tkinter import *
root = Tk()
def command():
print(checkbutton.cget("text"))
checkbutton = Checkbutton(root, text="Retrieve This Text")
button = Button(root, text="Ok", command=command)
checkbutton.pack()
button.pack()
root.mainloop()
You can use .cget()
to retrieve the value of a Tkinter
attribute. In the case above, you are printing the attribute text
from the variable checkbutton
which contains a predefined Tkinter
Checkbutton
element.
You can also do this directly from the Checkbutton
by assigning a command to it. Meaning that the value would be received every time the Checkbutton
s state updated
from tkinter import *
root = Tk()
def command():
print(checkbutton.cget("text"))
checkbutton = Checkbutton(root, text="Retrieve This Text", command=command)
checkbutton.pack()
root.mainloop()
Upvotes: 1