Please help! As it says in the title - I can't get checkbox' variable value.
def init_widgets(self):
ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10)
...
cbcc = ttk.Checkbutton(root, text="Damage", onvalue="on", offvalue='off').place(x=235, y=12)
...
def insert_txt(self):
...
cbcd = StringVar()
cbcd.get()
print(cbcd)
if cbcd == "on":
self.damage
else:
Print delivers "PY_VAR2" and counting up from there with every time I click (PY_VAR3, etc.)
It seems in your code, the argument 'variable' in your Checkbutton is not bounded, furthermore to get the value from IntVar or StringVar you would use (IntVar.get(), StringVar().get()), you could use the next code as example to use Checkbutton widget.
'''
CheckBox Test
References:
http://effbot.org/tkinterbook/checkbutton.htm
'''
from tkinter import *
class App:
def __init__(self, master):
self.var = IntVar() #This is the variable bounded to checkbutton to
#get the checkbutton state value
#
frame = Frame(master)
frame.pack()
self.checkbutton = Checkbutton(frame, text="Hello Checkbutton",
command=self.say_hello, variable=self.var)
self.checkbutton.pack(side=LEFT)
#
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
def say_hello(self):
'''
Function Bounded to Checkbutton in command parameter, every click
either check or un-check print the current state of the checkbutton
'''
print("State Changed:", self.var.get())
if __name__ == '__main__':
root = Tk()
app = App(root)
#
root.mainloop()
root.destroy() # Quit the App when you click "Quit"
Every click on the check button, you will see printed in the console the value of the current state for the checkbutton. You can check the next reference to get an general overview tkinter widgets: http://effbot.org/tkinterbook/checkbutton.htm
I hope this snippet helps you.
Very Best Regards.
Related
I am trying to simulate a computer player "clicking" a button after a human user clicks a button In a grid of buttons. If I use the .after method the 'state' of the button change is delayed but it executes my check_state() method which doesn't detect the change. When I try time.sleep() method it prolongs the human click but still immediately invokes the 'auto' click regardless of where I put it in my code. I want a delay between the human click and 'auto' click.
I have tried widget.after(1000) which gives the desired delay of 'auto' click, but doesn't allow my the change to be seen by my check_state() function. I have tried time.sleep() which delays the execution of the human button click but the 'auto' click is still immediately invokes regardless of which order I place the sleep() function in relation to the call to auto_click(). I know there are better practices for this code implementation like using class based structure which I plan on using once my logic and functionality issues are resolved. My code is as follows:
import tkinter as tk
import random
def app():
def auto_click():
grid_state = get_grid_state()
possible_clicks = []
for i in range(0, len(grid_state)):
if grid_state[i] == " ":
possible_clicks.append(i)
#debug.config(text=possible_moves)
click = random.choice(possible_clicks)
buttons[click].after(1000, lambda: buttons[click].config(text = "auto", state=tk.DISABLED))
#time.sleep(1)
check_grid_state()
check_grid_full()
debug.config(text="test")
def onclick(*arg):
global is_full
buttons[arg[0]].config(text = "clicked", state=tk.DISABLED)
check_grid_state()
check_grid_full()
if not is_full:
auto_click()
def check_grid_full():
global is_full
result=[]
for i in range(len(buttons)):
result.append(buttons[i].cget('state'))
r = [*set(result)]
if r == ['disabled']:
is_full = True
grid_status.config(text=is_full)
else:
is_full = False
Retrieve the current state of the grid
def get_grid_state():
grid_state =[]
for i in range(len(buttons)):
grid_state.append(buttons[i].cget('text'))
return grid_state
Check grid state
def check_grid_state():
grid_states.config(text=get_grid_state())
Global Variables
is_full = False
buttons = []
c=0
Window
root = tk.Tk()
root.title("Title")
Heading
label = tk.Label(root, text="grid state", font = ("Ariel black",22, "bold"))
label.pack()
Grid Frame
frame = tk.Frame(root)
frame.pack()
for row in range(3):
for column in range(3):
buttons.append(tk.Button(frame, text=f" ", font=("arial", "22"), state=tk.ACTIVE, height=2, width=2, command=lambda c=c: onclick(c)))
buttons[c].grid(row=row, column=column)
c += 1
Status bar
grid_states = tk.Label(root, text=f"")
grid_states.pack()
grid_status = tk.Label(root, text=f"")
grid_status.pack()
#btn_is = tk.Label(root, text=f"")
#btn_is.pack()
Debugging output label
debug = tk.Label(root, text="debug")
debug.pack()
Event loop
root.mainloop()
if name == "main":
app()
I am trying to extract the content of the [Documentation] section as a string for comparision with other part in a Python script.
I was told to use Robot framework API https://robot-framework.readthedocs.io/en/stable/
to extract but I have no idea how.
However, I am required to work with version 3.1.2
Example:
*** Test Cases ***
ATC Verify that Sensor Battery can enable and disable manufacturing mode
[Documentation] E1: This is the description of the test 1
... E2: This is the description of the test 2
[Tags] E1 TRACE{Trace_of_E1}
... E2 TRACE{Trace_of_E2}
Extract the string as
E1: This is the description of the test 1
E2: This is the description of the test 2
Have a look at these examples. I did something similar to generate testplans descritio. I tried to adapt my code to your requirements and this could maybe work for you.
import os
import re
from robot.api.parsing import (
get_model, get_tokens, Documentation, EmptyLine, KeywordCall,
ModelVisitor, Token
)
class RobotParser(ModelVisitor):
def __init__(self):
# Create object with remarkup_text to store formated documentation
self.text = ''
def get_text(self):
return self.text
def visit_TestCase(self, node):
# The matched `TestCase` node is a block with `header` and
# `body` attributes. `header` is a statement with familiar
# `get_token` and `get_value` methods for getting certain
# tokens or their value.
for keyword in node.body:
# skip empty lines
if keyword.get_value(Token.DOCUMENTATION) == None:
continue
self.text += keyword.get_value(Token.ARGUMENT)
def visit_Documentation(self,node):
# The matched "Documentation" node with value
self.remarkup_text += node.value + self.new_line
def visit_File(self, node):
# Call `generic_visit` to visit also child nodes.
return self.generic_visit(node)
if __name__ == "__main__":
path = "../tests"
for filename in os.listdir(path):
if re.match(".*\.robot", filename):
model = get_model(os.path.join(path, filename))
robot_parser = RobotParser()
robot_parser.visit(model)
text=robot_parser._text()
The code marked as best answer didn't quite work for me and has a lot of redundancy but it inspired me enough to get into the parsing and write it in a much readable and efficient way that actually works as is. You just have to have your own way of generating & iterating through filesystem where you call the get_robot_metadata(filepath) function.
from robot.api.parsing import (get_model, ModelVisitor, Token)
class RobotParser(ModelVisitor):
def __init__(self):
self.testcases = {}
def visit_TestCase(self, node):
testcasename = (node.header.name)
self.testcases[testcasename] = {}
for section in node.body:
if section.get_value(Token.DOCUMENTATION) != None:
documentation = section.value
self.testcases[testcasename]['Documentation'] = documentation
elif section.get_value(Token.TAGS) != None:
tags = section.values
self.testcases[testcasename]['Tags'] = tags
def get_testcases(self):
return self.testcases
def get_robot_metadata(filepath):
if filepath.endswith('.robot'):
robot_parser = RobotParser()
model = get_model(filepath)
robot_parser.visit(model)
metadata = robot_parser.get_testcases()
return metadata
This function will be able to extract the [Documentation] section from the testcase:
def documentation_extractor(testcase):
documentation = []
for setting in testcase.settings:
if len(setting) > 2 and setting[1].lower() == "[documentation]":
for doc in setting[2:]:
if doc.startswith("#"):
# the start of a comment, so skip rest of the line
break
documentation.append(doc)
break
return "\n".join(documentation)
I have a list box with several rows attached to a window.
list_box = Gtk.ListBox()
list_box.insert(Gtk.Label('foo'), -1)
list_box.insert(Gtk.Label('bar'), -1)
list_box.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically
window = Gtk.Window()
window.add(list_box)
window.show_all()
When I call show_all(), the first row of the list is being selected automatically what I don't want to happen. How to prevent auto-selecting it?
I tried changing the order of the functions call
window.show_all()
window.add(list_box)
which broke the layout and the size of the window doesn't fit to the list.
I was running into this issue as well, I used the following code to do it:
listbox = Gtk.ListBox(margin=0)
listbox.set_selection_mode(Gtk.SelectionMode.NONE)
I can still click on each row and do a callback with the following, as well:
listbox.connect("row-activated", self.callback)
The ListBox has a property selection-mode, which you can set to Gtk.SELECTION_NONE. In this case none of the rows will be selected (and cannot be selected later). I don't know if that is what you want.
You can also call the method unselect_all, which will unselect all rows. For this to work, the ListBox must be in SELECT_MULTIPLE or SELECT_SINGLE mode.
This example seems to work completely as expected (i.e. no selection at the start, and if a line is selected, the button can unselect it). If in your installation it doesn't work, I would try to update your packages:
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.connect("delete-event", self.on_delete)
self.listbox = Gtk.ListBox()
self.listbox.insert(Gtk.Label('foo'), -1)
self.listbox.insert(Gtk.Label('bar'), -1)
self.listbox.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically
button = Gtk.Button("Clear selection")
button.connect("clicked", self.on_button_clicked)
vbox = Gtk.VBox()
vbox.pack_start(button, False, True, 0)
vbox.pack_start(self.listbox, False, True, 0)
self.add(vbox)
self.show_all()
Gtk.main()
def on_button_clicked(self, btn):
self.listbox.unselect_all()
def on_delete(self, win, event):
Gtk.main_quit()
def main():
w = MainWindow()
return 0
if __name__ == '__main__':
main()
A note about gtk3 themes: Some themes do not show selected rows at all. Particularly dark themes such as eg. FlatStudioDark, but also some light themes.
Add a dummy label to the top of your list_box and hide it:
dummyLabel = Gtk.Label('nothing') # workaround for focus of title entry
list_box.insert(dummyLabel, -1)
list_box.insert(Gtk.Label('foo'), -1)
list_box.insert(Gtk.Label('bar'), -1)
list_box.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically
window = Gtk.Window()
window.add(list_box)
window.show_all()
dummyLabel.hide()
Gtk.main()
The result:
result
I tried to program an app in tkinter that would load random lines from a file you select from a pull down menu and display the selected line in a text window.
It seems like the variable "var" in insert_text does not return the selected "option" but rather an "empty" string resulting in a the following error:
"File not found error" (FileNotFoundError: [Errno2] No such file or
directory: '').
Please help!
#!/usr/bin/env python
# Python 3
import tkinter
from tkinter import ttk
import random
class Application:
def __init__(self, root):
self.root = root
self.root.title('Random Stuff')
ttk.Frame(self.root, width=450, height=185).pack()
self.init_widgets()
var = tkinter.StringVar(root)
script = var.get()
choices = ['option1', 'option2', 'option3']
option = tkinter.OptionMenu(root, var, *choices)
option.pack(side='right', padx=10, pady=10)
def init_widgets(self):
ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10)
self.txt = tkinter.Text(self.root, width='45', height='5')
self.txt.place(x=10, y=50)
def insert_txt(self):
var = tkinter.StringVar(root)
name = var.get()
line = random.choice(open(str(name)).readlines())
self.txt.insert(tkinter.INSERT, line)
if __name__ == '__main__':
root = tkinter.Tk()
Application(root)
root.mainloop()
That's because you're just creating an empty StringVar that isn't modified later, thus returning an empty string.
The OptionMenu takes the command parameter that calls the specified method every time another option is selected. Now, you can call a method like this, replacing you insert_txt:
def __init__(self):
# ...
self.var = tkinter.StringVar()
self.options = tkinter.OptionMenu(root, var, *choices, command=self.option_selected)
# ...
def option_selected(self, event):
name = self.var.get()
# The stuff you already had
Additionally, you have to empty the Text widget, otherwise the previous text would stay. I think the Entry widget is better for that, too.
I want to catch all tries to close some specific existing Cocoa window and add some own handler (which might indeed really close it or do something different).
I had different solutions in mind to do this. One was:
I want to replace the window close button of an existing Cocoa window at runtime with an own close widget where I can add some own code.
Right now, I have this code:
import objc
_NSThemeCloseWidget = objc.lookUpClass("_NSThemeCloseWidget")
def find_close_widget(window):
contentView = window.contentView()
grayFrame = contentView.superview()
for i in range(len(grayFrame.subviews())):
v = grayFrame.subviews()[i]
if isinstance(v, _NSThemeCloseWidget):
return v, i, grayFrame
class CustomCloseWidget(_NSThemeCloseWidget):
pass
def replace_close_widget(window, clazz=CustomCloseWidget):
v, i, grayFrame = find_close_widget(window)
newv = clazz.alloc().init()
grayFrame.subviews()[i] = newv
However, this doesn't seem quite right. (It crashes.)
The close widget isn't the only way to close the window. There's a public API to obtain the widget, so you don't need to go rifling through the frame view's subviews, but that's the wrong path anyway.
The right way is to make an object to be the window's delegate, and interfere with the window's closure there. Ideally, you should set the window's delegate in between creating the window and ordering it in.
I am going another route now. This is partly Chrome related but it can easily be adopted elsewhere. I wanted to catch several actions for closing the window as early as possible to avoid any other cleanups or so which resulted in the window being in a strange state.
def check_close_callback(obj):
# check ...
return True # or:
return False
import objc
BrowserWindowController = objc.lookUpClass("BrowserWindowController")
# copied from objc.signature to avoid warning
def my_signature(signature, **kw):
from objc._objc import selector
kw['signature'] = signature
def makeSignature(func):
return selector(func, **kw)
return makeSignature
windowWillCloseSig = "c12#0:4#8" # BrowserWindowController.windowWillClose_.signature
commandDispatchSig = "v12#0:4#8"
class BrowserWindowController(objc.Category(BrowserWindowController)):
#my_signature(windowWillCloseSig)
def myWindowShouldClose_(self, sender):
print "myWindowShouldClose", self, sender
if not check_close_callback(self): return objc.NO
return self.myWindowShouldClose_(sender) # this is no recursion when we exchanged the methods
#my_signature(commandDispatchSig)
def myCommandDispatch_(self, cmd):
try: print "myCommandDispatch_", self, cmd
except: pass # like <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\u2026' in position 37: ordinal not in range(128)
if cmd.tag() == 34015: # IDC_CLOSE_TAB
if not check_close_callback(self): return
self.myCommandDispatch_(cmd)
from ctypes import *
capi = pythonapi
# id objc_getClass(const char *name)
capi.objc_getClass.restype = c_void_p
capi.objc_getClass.argtypes = [c_char_p]
# SEL sel_registerName(const char *str)
capi.sel_registerName.restype = c_void_p
capi.sel_registerName.argtypes = [c_char_p]
def capi_get_selector(name):
return c_void_p(capi.sel_registerName(name))
# Method class_getInstanceMethod(Class aClass, SEL aSelector)
# Will also search superclass for implementations.
capi.class_getInstanceMethod.restype = c_void_p
capi.class_getInstanceMethod.argtypes = [c_void_p, c_void_p]
# void method_exchangeImplementations(Method m1, Method m2)
capi.method_exchangeImplementations.restype = None
capi.method_exchangeImplementations.argtypes = [c_void_p, c_void_p]
def method_exchange(className, origSelName, newSelName):
clazz = capi.objc_getClass(className)
origMethod = capi.class_getInstanceMethod(clazz, capi_get_selector(origSelName))
newMethod = capi.class_getInstanceMethod(clazz, capi_get_selector(newSelName))
capi.method_exchangeImplementations(origMethod, newMethod)
def hook_into_windowShouldClose():
method_exchange("BrowserWindowController", "windowShouldClose:", "myWindowShouldClose:")
def hook_into_commandDispatch():
method_exchange("BrowserWindowController", "commandDispatch:", "myCommandDispatch:")
This code is from here and here.