Switchable Radio Buttons (editing a command) - python

I'm a bit stuck on how to write the correct syntax for editing a command.
way down in my radioOn and radioOff commands, I would like the enable / disable checkbox to enable or disable the radio buttons.
from functools import partial
import maya.cmds as cmds
def one ():
print '1'
def two ():
print '2'
winID = 'xx'
if cmds.window(winID, exists=True):
cmds.deleteUI(winID)
window = cmds.window(winID, sizeable = False, title="Resolution Switcher", widthHeight=(300, 100) )
cmds.columnLayout( )
cmds.text (label = '')
cmds.text (label = '')
cmds.checkBoxGrp( cat = (1,'left', 20), ncb = 1, l1=' DISABLE', offCommand = partial(radioOn, a), onCommand = partial(radioOff, a) )
a = cmds.radioButtonGrp( cat = [(1,'left', 90),(2, 'left', 100)], numberOfRadioButtons=2, on1 = 'one ()' , on2 = 'two ()' )
cmds.text (label = '')
def radioOff (a, *args):
print 'radios off'
a(ed=True, enable=False)
def radioOn (a, *args):
print 'radios on'
a(ed=True, enable=False)
cmds.showWindow( window )
I've tried to get an idea from examples such as the one shown here, but
but when I put down cmds.radioButtonGrp(a, ed=True, enable=False) it just keeps creating new radio buttons, not unlike what was shown in the example with float fields.
bottom line is - I just want the radio buttons to be greyed out and disabled whenever I hit the checkbox. Speaking of which - Is it possible to grey out the radio buttons the same way float fields can? I noticed that disabling them only makes them unclickable - but not greyed out.
Thank you in advance.

from functools import partial
import maya.cmds as cmds
def one (*args):
print '1'
def two (*args):
print '2'
def radioSwitch (a, state, *args):
if state:
cmds.radioButtonGrp(a, e=True, enable=False)
else:
cmds.radioButtonGrp(a, e=True, enable=True)
winID = 'xx'
if cmds.window(winID, exists=True):
cmds.deleteUI(winID)
window = cmds.window(winID, sizeable = False, title="Resolution Switcher", widthHeight=(300, 100) )
cmds.columnLayout( )
cmds.text (label = '')
cmds.text (label = '')
cb_disable = cmds.checkBoxGrp( cat = (1,'left', 20), ncb = 1, l1=' DISABLE', offCommand = "" , onCommand = "" )
a = cmds.radioButtonGrp( cat = [(1,'left', 90),(2, 'left', 100)], enable=True, numberOfRadioButtons=2, on1 = one , on2 = two )
cmds.checkBoxGrp(cb_disable, e=1, offCommand = partial(radioSwitch, a, False))
cmds.checkBoxGrp(cb_disable, e=1, onCommand = partial(radioSwitch, a, True))
cmds.text (label = '')
cmds.showWindow( window )

Related

"Allocating size to..." GTK Warning when using Gtk.TreeView inside Gtk.ScrolledWindow

I'm receiving the following warnings in my GTK 3 application:
Gtk-WARNING **: Allocating size to __main__+MCVEWindow 0000000004e93b30 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
The warnings occurs when Gtk.ScrolledWindow containing Gtk.TreeView is attached to the grid, the grid itself is attached to the gtk.ApplicationWindow and there are enough elements for the scrollbar to actually appear. If there aren't enough elements to make it scrollable, the warning doesn't appear.
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk as gtk
class MCVEWindow(gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._tree_view = gtk.TreeView()
self._tree_view.set_hexpand(True)
self._tree_view.set_vexpand(True)
self.populate_tree_view() # populate tree view with fake items
window_column = gtk.TreeViewColumn(
"Window", gtk.CellRendererText(),
text=0
)
window_column.set_resizable(True)
handle_column = gtk.TreeViewColumn(
"Handle", gtk.CellRendererText(),
text=1
)
class_column = gtk.TreeViewColumn(
"Class name", gtk.CellRendererText(),
text=2
)
self._tree_view.append_column(window_column)
self._tree_view.append_column(handle_column)
self._tree_view.append_column(class_column)
scrolled_tree_view = gtk.ScrolledWindow()
scrolled_tree_view.add(self._tree_view)
toolbar = gtk.Toolbar()
expand_tree_view_button = gtk.ToolButton(icon_name="list-add")
expand_tree_view_button.connect(
"clicked",
lambda e: self._tree_view.expand_all()
)
collapse_tree_view_button = gtk.ToolButton(icon_name="list-remove")
collapse_tree_view_button.connect(
"clicked",
lambda e: self._tree_view.collapse_all()
)
toolbar.insert(expand_tree_view_button, -1)
toolbar.insert(collapse_tree_view_button, -1)
status_bar = gtk.Statusbar()
status_bar.push(
status_bar.get_context_id("Status message"),
"A status message."
)
self._master_grid = gtk.Grid()
self._master_grid.attach(toolbar, 0, 0, 1, 1)
self._master_grid.attach(scrolled_tree_view, 0, 1, 1, 1)
self._master_grid.attach(status_bar, 0, 2, 1, 1)
self.add(self._master_grid)
self.connect("delete-event", gtk.main_quit)
self.show_all()
def populate_tree_view(self):
tree_store = gtk.TreeStore(str, str, str)
# Warnings don't occur when there are less than 100 "root" items
for i in range(100):
item1 = tree_store.append(
None,
["Window " + str(i + 1), "12345678", "ClassName"]
)
for j in range(3):
item2 = tree_store.append(
item1,
["Window " + str(i + 1) + str(i + 2),
"12345678",
"ClassName"]
)
for k in range(5):
tree_store.append(
item2,
["Window " + str(i + 1) + str(j + 1) + str(k + 1),
"12345678",
"ClassName"]
)
self._tree_view.set_model(tree_store)
class MCVEApp(gtk.Application):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_activate(self):
MCVEWindow()
gtk.main()
if __name__ == "__main__":
MCVEApp().run()
You should be able to copy, paste and run this code if you have environment set up.
The warnings don't follow any specific pattern, sometimes there is one warning, sometimes two or more. The warrnings also pop up whenever I expand all tree items.
GTK version is 3.22.18
What could cause these warnings?
I received the answer on the GTK App dev mailing list which lead me to the solution:
Attaching TreeView to GTK Grid which is then added to the ScrolledWindow solved the issue for me.
Instead of this
scrolled_tree_view = gtk.ScrolledWindow()
scrolled_tree_view.add(self._tree_view)
you need to do the following
scrolled_tree_view = gtk.ScrolledWindow()
grid = gtk.Grid()
grid.attach(self._tree_view, 0, 0, 1, 1)
scrolled_tree_view.add(grid)
Unfortunately, this isn't documented anywhere.

optionMenu is not returning value

I have written up a simple UI that requires user to select something from a drop-down list, then using that selection, the code will executes the rest of the stuff
Right now, I am having 2 issues..
1. The 'value' is not exactly returning, as soon as a Format is selected and the OK button is hit... Am I missing something?
2. How can I make my UI closes upon a OK button has been selected?
import maya.cmds as cmds
def mainCode():
...
...
print "UI popping up"
showUI()
print "A format has been selected"
cmds.optionMenu('filmbackMenu', edit = True, value = xxx ) # <-- I want to grab the value from the menu selection and input into this 'value' flag
...
...
def showUI():
if cmds.window("UI_MainWindow", exists = True):
cmds.deleteUI("UI_MainWindow")
cmds.window("UI_MainWindow", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
cmds.columnLayout("UI_MainLayout", w = 300, h =500)
cmds.optionMenu("UI_FormatMenu", w = 250, label = "Select a Format")
list01 = ['itemA-01', 'itemB-02', 'itemC-02', 'itemD-01', 'itemE-01', 'itemF-03']
for x in list01:
cmds.menuItem(label = str(x))
cmds.button("UI_SelectButton", label = "OK", w = 200, command=ObjectSelection)
cmds.showWindow("UI_MainWindow") #shows window
def ObjectSelection(*args):
currentFormat = cmds.optionMenu("UI_FormatMenu", query=True, value=True)
print currentFormat
return currentFormat
Use python dictionnaries or class to pass data in your script.
I really don't understand what the problem is.
When you say : "The 'value' is not exactly returning", what do you mean ? Can you tell us what do you get and what do you expect ?
def mainCode():
...
...
showUI()
cmds.optionMenu('filmbackMenu', edit = True, value = xxx ) # <-- I want to grab the value from the menu selection and input into this 'value' flag
...
Here the value selection from the "input value", I guess it is :
cmds.optionMenu('filmbackMenu', edit = True, value = ObjectSelection())
But as there is not filmbackMenu in your code, I'm not sure.
Your second question has been answered on google groups by Justin. You just have to do :
def ObjectSelection(*args):
currentFormat = cmds.optionMenu("UI_FormatMenu", query=True, value=True)
cmds.deleteUI("UI_MainWindow")#close the UI
print currentFormat
return currentFormat
Or maybe "upon a OK button has been selected?" doesn't mean "OK button pressed" ?
If you want to see how use dictionnaries, you can read this other post where I have answered : Maya Python - Using data from UI
You are in a good path to using partial, I recommend you to read about it : Calling back user input values inside maya UI
--- EDIT ---
I tried to create a fully functionnal example :
import maya.cmds as cmds
uiDic = {}
uiDic['this']= 1
def ui_refresh(*args):
uiDic['this'] = cmds.optionMenu("UI_FormatMenu", query=True, value=True)
return uiDic['this']
def showUI():
if cmds.window("UI_MainWindow", exists = True):
cmds.deleteUI("UI_MainWindow")
cmds.window("UI_MainWindow", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
cmds.columnLayout("UI_MainLayout", w = 300, h =500)
cmds.optionMenu("UI_FormatMenu", w = 250, label = "Select a Format")
list01 = ['itemA-01', 'itemB-02', 'itemC-02', 'itemD-01', 'itemE-01', 'itemF-03']
for x in list01:
cmds.menuItem(label = str(x))
cmds.button("UI_SelectButton", label = "OK", w = 200, command=ObjectSelection)
uiDic['om_filmback'] = cmds.optionMenu('filmbackMenu' )
list01 = ['itemA-01', 'itemB-02', 'itemC-02', 'itemD-01', 'itemE-01', 'itemF-03']
for x in list01:
cmds.menuItem(label = str(x))
cmds.showWindow("UI_MainWindow") #shows window
def ObjectSelection(*args):
cmds.optionMenu(uiDic['om_filmback'], edit = True, value=ui_refresh())
showUI()

Python sqlite3, tkinter display multible rows

I am new to python and recently i make dictionary using Python and Sqlite3 with tkinter.
When I run the code it returns multiple line in IDLE but in the GUI its only display the last result. I would like to display all the information in the GUI. Thanks you for any help and suggestion.
import tkinter
import sqlite3
class Dictionary:
def __init__(self,master =None):
self.main_window = tkinter.Tk()
self.main_window.title("Lai Mirang Dictionary")
self.main_window.minsize( 600,400)
self.main_window.configure(background = 'paleturquoise')
self.frame1 = tkinter.Frame()
self.frame2= tkinter.Frame(bg = 'red')
self.frame3 =tkinter.Text( foreground = 'green')
self.frame4 = tkinter.Text()
self.lai_label = tkinter.Label(self.frame1,anchor ='nw',font = 'Times:12', text = 'Lai',width =25,borderwidth ='3',fg='blue')
self.mirang_label = tkinter.Label(self.frame1,anchor ='ne',font = 'Times:12', text = 'Mirang',borderwidth ='3',fg ='blue')
self.lai_label.pack(side='left')
self.mirang_label.pack(side = 'left')
self.kawl_buttom= tkinter.Button(self.frame2 ,fg = 'red',font = 'Times:12',text ='Kawl',command=self.dic,borderwidth ='3',)
self.lai_entry = tkinter.Entry(self.frame2, width= 28, borderwidth ='3',)
self.lai_entry.focus_force()
self.lai_entry.bind('<Return>', self.dic,)
self.lai_entry.configure(background = 'khaki')
self.lai_entry.pack(side='left')
self.kawl_buttom.pack(side = 'left')
self.value = tkinter.StringVar()
self.mirang_label= tkinter.Label(self.frame3,font = 'Times:12',fg = 'blue',textvariable = self.value,justify = 'left',wraplength ='260',width = 30, height = 15,anchor = 'nw')
self.mirang_label.pack()
self.mirang_label.configure(background = 'seashell')
self.copyright_label = tkinter.Label(self.frame4,anchor ='nw',font = 'Times:12:bold',text = "copyright # cchristoe#gmail.com",width = 30,borderwidth = 3, fg = 'purple',)
self.copyright_label.pack()
self.frame1.pack()
self.frame2.pack()
self.frame3.pack()
self.frame4.pack()
tkinter.mainloop()
self.main_window.quit()
def dic(self, event = None):
conn = sqlite3.connect('C:/users/christoe/documents/sqlite/laimirangdictionary.sqlite')
c = conn.cursor()
kawl = self.lai_entry.get()
kawl = kawl + '%'
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
dic=Dictionary()
You need to change:
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
To:
for member in c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,)):
current_text = self.value.get()
new_text = current_text +( "\n" if current_text else "") +" ".join(member)
self.value.set(new_text)
The new version gets the current value of the StringVar value and then appends the results returned with a space inbetween for each row returned with each row on its own line. What you were doing however involved just updating the StringVar to be the current member object, and therefore it only ever had the last values.
This is how it looks with more than one line:

PyGTK custom ComboBox behavior

I'm trying to create a custom ComboBox that behaves like the one in here: http://chir.ag/projects/name-that-color/
I've got two problems right now:
I can't seem to find a way to have a scrollbar on the side; the gtk.rc_parse_string function should do that, since the ComboBox widget has a "appears-as-list" style property, but my custom widget seems unaffected for some reason.
When you select a color from my widget, then click the ComboBox again, instead of showing the selected item and its neighbours, the scrolled window starts from the top, for no apparent reason.
This is the code, you can pretty much ignore the __load_name_palette method. You need the /usr/share/X11/rgb.txt file to run this code, it looks like this: http://pastebin.com/raw.php?i=dkemmEdr
import gtk
import gobject
from os.path import exists
def window_delete_event(*args):
return False
def window_destroy(*args):
gtk.main_quit()
class ColorName(gtk.ComboBox):
colors = []
def __init__(self, name_palette_path, wrap_width=1):
gtk.ComboBox.__init__(self)
liststore = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
gobject.TYPE_STRING)
name_palette = self.__load_name_palette(name_palette_path)
for c in name_palette:
r, g, b, name = c
if ((r + g + b) / 3.) < 128.:
fg = '#DDDDDD'
else:
fg = '#222222'
bg = "#%02X%02X%02X" % (r, g, b)
liststore.append((name, bg, fg))
self.set_model(liststore)
label = gtk.CellRendererText()
self.pack_start(label, True)
self.set_attributes(label, background=1, foreground=2, text=0)
self.set_wrap_width(wrap_width)
if len(name_palette) > 0:
self.set_active(0)
self.show_all()
def __load_name_palette(self, name_palette_path):
if exists(name_palette_path):
try:
f = open(name_palette_path,'r')
self.colors = []
palette = set()
for l in f:
foo = l.rstrip().split(None,3)
try:
rgb = [int(x) for x in foo[:3]]
name, = foo[3:]
except:
continue
k = ':'.join(foo[:3])
if k not in palette:
palette.add(k)
self.colors.append(rgb + [name])
f.close()
return self.colors
except IOError as (errno, strerror):
print "error: failed to open {0}: {1}".format(name_palette_path, strerror)
return []
else:
return []
if __name__ == '__main__':
win = gtk.Window()
#colname = ColorName('./ntc.txt')
colname = ColorName('/usr/share/X11/rgb.txt')
gtk.rc_parse_string("""style "mystyle" { GtkComboBox::appears-as-list = 1 }
class "GtkComboBox" style "mystyle" """)
print 'appears-as-list:', colname.style_get_property('appears-as-list')
model = gtk.ListStore(gobject.TYPE_STRING)
hbox = gtk.HBox()
win.add(hbox)
hbox.pack_start(colname)
win.connect('delete-event', window_delete_event)
win.connect('destroy', window_destroy)
win.show_all()
gtk.main()
The problem was the self.show_all() line. Also, you can't have a list AND a wrap_width != 1

Text in gtk.ComboBox without active item

The following PyGTk code, gives a combo-box without an active item.
This serves a case where we do not want to have a default,
and force the user to select.
Still, is there a way to have the empty combo-bar show something like:
"Select an item..."
without adding a dummy item?
import gtk
import sys
say = sys.stdout.write
def cb_changed(w):
say("Active index=%d\n" % w.get_active())
topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()
ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)
ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))
vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()
gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)
Huge hack ahead (I just added this to your program):
import gtk
import sys
say = sys.stdout.write
def cb_changed(w):
say("Active index=%d\n" % w.get_active())
topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()
ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)
#- Begin of the hack ----------------------------------
def special_empty_text (cell_view, event):
if cell_view.window is None:
return False
row = cell_view.get_displayed_row ()
if row is not None:
return False
layout = cell_view.create_pango_layout ('bla bla bla')
context = cell_view.window.cairo_create ()
xpad = 0
ypad = 0
renderer = cell_view.get_cells () [0]
if renderer is not None:
xpad = renderer.props.xpad
ypad = renderer.props.ypad
context.move_to (cell_view.allocation.x + xpad, cell_view.allocation.y + ypad)
context.set_source_rgb (0.6, 0.6, 0.6)
context.show_layout (layout)
return True
combo.child.connect ('expose-event', special_empty_text)
#- End of the hack ----------------------------------
ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))
vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()
gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)
Don't see a nicer way.

Categories

Resources