How can I establish a default String value on a Tkinter Spinbox? - python-2.7

I have read a good solution for establishing a default numerical value on a Tkinter Spinbox widget when you use the from_ to options. But I have not seen a single one that can help establish a value (numerical or string) from a tuple.
My code is as follows, and is intended to set a default value in a Tkinter Spinbox widget from a tuple:
from Tkinter import *
root = Tk()
root.geometry('200x200+50+50')
root.title('Prueba')
t = ('One', 'Two', 'Three', 'Four', 'Five')
v = t[3]
var = StringVar()
var.set(v)
sb = Spinbox(root, values=t, textvariable=var, width=10)
sb.place(x=5, y=15)
root.mainloop()
Another variant that I have tried is the following:
from Tkinter import *
root = Tk()
root.geometry('200x200+50+50')
root.title('Prueba')
var = StringVar()
var.set('Four')
sb = Spinbox(root, ('One', 'Two', 'Three', 'Four', 'Five'), textvariable=var, width=10)
sb.place(x=5, y=15)
root.mainloop()
The only way the set method works on Spinbox (and which I took from here) is the following and only works with numbers and within a range established as options in the Spinbox widget:
from Tkinter import *
root = Tk()
root.geometry('200x200+50+50')
root.title('Prueba')
var = StringVar()
var.set(4)
sb = Spinbox(root, from_=1, to=5, textvariable=var, width=10)
sb.place(x=5, y=15)
root.mainloop()
Can please anyone help me to find out how to establish a default value in a Tkinter Spinbox from a Tuple? I will appreciate that greatly!

If you move the line var.set(v) to be after creating the widget, the default value will be set.
var = StringVar()
sb = Spinbox(root, values=t, textvariable=var, width=10)
var.set(v)

Related

replacing a new interface with old one in tkinter

I've created a class that has a function called mainScreen(). It simply prints the main screen with two buttons on it. If you press any button, it must go to another function called signup(). I want to clear the whole frame and create new widgets but I can't clear the widgets
class graphics:
def __init__(self, master):
self.root = master
def mainscreen(self):
helv36 = tkFont.Font(family='Century Gothic', size=20)
mainFrame = Frame(self.root)
mainFrame.config(relief='sunken', width=1280, height=720, bg='light
blue')
mainFrame.pack(expand='yes', fill='both')
inButton = Button(mainFrame, text = "Sign up", bd = 10, relief =
GROOVE, font = helv36)
inButton.bind("<Button-1>", self.signup)
inButton.place(bordermode = OUTSIDE, width =160, height = 60, x =
600, y = 300)
upButton = Button(mainFrame, text = "Sign in", bd = 10, relief =
GROOVE, font = helv36)
upButton.bind("<Button-1>", self.signup)
upButton.place(bordermode = OUTSIDE, width =160, height = 60, x =
600, y = 400)
mainFrame.pack_propagate(FALSE)
self.root.mainloop()
def signup(self,event):
signUpShow = Frame(self.root)
signUpShow.config(relief='sunken', width=1280, height=720, bg='light
yellow')
signUpShow.pack(expand='yes', fill='both')
You __init__ needs to have its code indented and it needs a call to mainscreen. The solution to mainFrame being local within mainscreen is to make it also an attribute.
self.mainframe = mainFrame = Frame(self.root)
Then you can access self.mainframe within signup.

How to make a toggle cell in GTK TreeView editable by using Glade?

I'm using Glade 3.20 but i don't known how to make a toggle column editable. I do not see any options.
screenshots
Please help me!
Look at this CellRendererToggle usage example (in python).
The source (in case the link breaks someday):
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class CellRendererToggleWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="CellRendererToggle Example")
self.set_default_size(200, 200)
self.liststore = Gtk.ListStore(str, bool, bool)
self.liststore.append(["Debian", False, True])
self.liststore.append(["OpenSuse", True, False])
self.liststore.append(["Fedora", False, False])
treeview = Gtk.TreeView(model=self.liststore)
renderer_text = Gtk.CellRendererText()
column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0)
treeview.append_column(column_text)
renderer_toggle = Gtk.CellRendererToggle()
renderer_toggle.connect("toggled", self.on_cell_toggled)
column_toggle = Gtk.TreeViewColumn("Toggle", renderer_toggle, active=1)
treeview.append_column(column_toggle)
renderer_radio = Gtk.CellRendererToggle()
renderer_radio.set_radio(True)
renderer_radio.connect("toggled", self.on_cell_radio_toggled)
column_radio = Gtk.TreeViewColumn("Radio", renderer_radio, active=2)
treeview.append_column(column_radio)
self.add(treeview)
def on_cell_toggled(self, widget, path):
self.liststore[path][1] = not self.liststore[path][1]
def on_cell_radio_toggled(self, widget, path):
selected_path = Gtk.TreePath(path)
for row in self.liststore:
row[2] = (row.path == selected_path)
win = CellRendererToggleWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

Text giving constantly feedback about current selection

I am writing a script which has an UI in Maya. I have a text box that is supposed to constantly update based on the last item in the users selection list. How would I go about something that constantly keeps checken whithout having the user to push a button or something manually to call a function.
Thx
Edit: Cool that is what I was looking for. Thx. Your script works just fine. I tried implementing that into my big script which resulted in that every button in the UI had to be pushed twice in order to take effect. But I will deal with that later. However testing my own version in a seperate script as follows sometimes produces the following error: 'sl' must be passed a boolean argument
#________________________________________________________________________________________________________________________________________________
import maya.cmds as cmds
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_label(*_):
upCurrentObjectSel = cmds.ls(sl=True)
upCurrentObjectSelShapes = cmds.listRelatives(upCurrentObjectSel)
upLastobj = upCurrentObjectSelShapes[-1]
print upLastobj
cmds.text(curSelTxt, e=True, label = upLastobj)
cmds.scriptJob(event=("SelectionChanged", update_label), p= curSelTxt)
cmds.showWindow(idManagerUI)
Also, making two of these ScriptJobs makes the script stop working properly entirely.
#________________________________________________________________________________________________________________________________________________
import maya.cmds as cmds
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelObjTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
curSelShadTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_obj_label(*_):
upCurrentObjectSel = cmds.ls(sl=True)
upCurrentObjectSelShapes = cmds.listRelatives(upCurrentObjectSel)
upLastobj = upCurrentObjectSelShapes[-1]
objID = cmds.getAttr(upLastobj + '.vrayObjectID')
print objID
cmds.text(curSelObjTxt, e=True, label = objID)
def update_shader_label(*_):
upCurrentShaderSel = cmds.ls(sl=True, type= shaderTypes)
upCurrentShaderSelLast = upCurrentShaderSel[-1]
shadID = cmds.getAttr(upCurrentShaderSelLast + '.vrayMaterialId')
cmds.text(curSelShadTxt, e=True, label = shadID)
print shadID
cmds.scriptJob(event=("SelectionChanged", update_obj_label), p= curSelObjTxt)
cmds.scriptJob(event=("SelectionChanged", update_shader_label), p= curSelShadTxt)
cmds.showWindow(idManagerUI)
Edit:
still your latest version of the script produces the error from time to time.
Also, I noticed in my own version of it, that it sometimes works lovely, then not at all, once I e.g. switched my active window to Firefox or so and then get back to Maya, and sometimes it does not work at all. That is with just one of the functions in my script. With both of them (s.below) it is totally unusable. Very unstable results.
import maya.cmds as cmds
def curSelTxtShower():
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelObjTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
curSelShadTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_obj_label(*_):
upCurrentObjectSelShapes = cmds.listRelatives(s=True) or ["nothing selected"]
upLastobj = upCurrentObjectSelShapes[-1]
if upLastobj is not "nothing selected":
if cmds.attributeQuery('vrayObjectID', node = upLastobj, ex = True) is True:
objID = cmds.getAttr(upLastobj + '.vrayObjectID')
cmds.text(curSelObjTxt, e=True, label = objID)
else:
cmds.text(curSelObjTxt, e=True, label = 'curSel has no ObjID assigned')
def update_shader_label(*_):
upCurrentShaderSel = cmds.ls(sl=True, type= shaderTypes)
upCurrentShaderSelLast = upCurrentShaderSel[-1]
if cmds.attributeQuery('vrayMaterialId', node = upCurrentShaderSelLast, ex = True) is True:
shadID = cmds.getAttr(upCurrentShaderSelLast + '.vrayMaterialId')
cmds.text(curSelShadTxt, e=True, label = shadID)
print shadID
else:
cmds.text(curSelShadTxt, e=True, label = 'curSel has no MatID assigned')
cmds.scriptJob(event=("SelectionChanged", lambda *x: update_obj_label()), p= curSelObjTxt)
cmds.scriptJob(event=("SelectionChanged", lambda *x: update_shader_label()), p= curSelShadTxt)
cmds.showWindow(idManagerUI)
curSelTxtShower()
You need to use a scriptJob to watch for selection change events and respond. You'll want to parent the scriptJob to a particular piece of UI so it deletes itself when the UI object goes away.
An absolutely minimal example looks like this:
import maya.cmds as cmds
wind = cmds.window()
col = cmds.columnLayout()
txt = cmds.text(label="", width = 240)
def update_label(*_):
cmds.text(txt, e=True, label = str(cmds.ls(sl=True)))
cmds.scriptJob(event=("SelectionChanged", update_label), p= txt)
cmds.showWindow(wind)
Edit
This version of OP's code helps avoid the false error message. the actual error was happening when due to an empty selection - but the scriptJob falsely reports it in the previous line:
def scoped():
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_label(*_):
# listRelatives works off the current selection already
upCurrentObjectSelShapes = cmds.listRelatives(s=True) or ["nothing selected"]
upLastobj = upCurrentObjectSelShapes[-1]
cmds.text(curSelTxt, e=True, label = upLastobj)
cmds.showWindow(idManagerUI)
cmds.scriptJob(event=("SelectionChanged", update_label), p= idManagerUI)
scoped()

Tkinter/python: how to create a checkbutton to select all checkbuttons

I created a list of checkboxes with Tkinter but I would like to select all checkboxes with a single checkbox.
Here is part of my code:
root = tk.Tk()
root.title("SOMETHING")
buttons=[]
#If it is checked, then run the file
def callback():
for var, name in buttons:
if var.get():
subprocess.call("python " + "scripts/" + name)
for name in os.listdir("scripts"):
if name.endswith('.py') or name.endswith('.pyc'):
if name not in ("____.py", "_____.pyc"):
var = tk.BooleanVar()
cb = tk.Checkbutton(root, text=name, variable=var)
cb.pack()
buttons.append((var,name))
def select_all():
if var1.get():
for i in cb:
i.select(0,END)
def deselect_all():
if var2.get():
for i in cb:
i.deselect_set(0,END)
var1=tk.BooleanVar()
selectButton = tk.Checkbutton(root, text="Select All", command=select_all, variable=var1)
selectButton.pack()
var2=tk.BooleanVar()
deselectButton = tk.Checkbutton(root, text="None", command=deselect_all, variable=var2)
deselectButton.pack()
submitButton = tk.Button(root, text="Run", command=callback)
submitButton.pack()
root.mainloop()
When I run the file and press "select all", I get this error: 'str' object has no attribute 'select'.
Please help thanks :)
I have reviewed your code and attached a working tkinter code. Will leave you to resolve the issue with using subprocess.
My main comment is that your use of control variable and how to use it to get and set their value was inappropriate. I have remove the unnecessary codes. Also, shown you how to extract information from your list. Hope this helps your tkinter coding journey.
Working code:
import tkinter as tk
import os, subprocess
#If it is checked, then run the file
def callback():
if var.get():
for i in buttons:
cmd = "python3 " + filedir +"/" + i[1] #Note:Runs python3 and not python2
print(cmd)
subprocess.call(cmd)
def select_all(): # Corrected
for item in buttons:
v , n = item
if v.get():
v.set(0)
else:
v.set(1)
root = tk.Tk()
root.title("SOMETHING")
filedir = 'test'
buttons=[]
for name in os.listdir(filedir):
if name.endswith('.py') or name.endswith('.pyc'):
if name not in ("____.py", "_____.pyc"):
var = tk.IntVar()
var.set(0)
cb = tk.Checkbutton(root, text=name, variable=var)
cb.pack()
buttons.append((var,name))
var1=tk.IntVar()
var1.set(0)
selectButton = tk.Checkbutton(root, text="Select All", command=select_all,
variable=var1)
selectButton.pack()
submitButton = tk.Button(root, text="Run", command=callback)
submitButton.pack()
root.mainloop()

How to show and hide QtGui.QGridLayout in PySide

Here I am creating a layout called _grid and putting few labels and slider in the layout .
Now I want this layout to be hide first then onclick I want to show it .
If there is any simple function associated with QtGui.QGridLayout to show and hide.
I googled and found this is available for QWidget by QWidget.hide()
class TimeSlider (QtGui.QVBoxLayout):
def __init__ (self):
QtGui.QVBoxLayout.__init__ (self)
# Put everything in a grid
_grid = QtGui.QGridLayout ()
self.addLayout (_grid)
# Slider limit labels
_grid.addWidget (QtGui.QLabel (''), 0, 0)
_labelLayout = QtGui.QHBoxLayout ()
_grid.addLayout (_labelLayout, 0, 1)
self.lower = QtGui.QLabel ('LOW')
_labelLayout.addWidget (self.lower)
self.higher = QtGui.QLabel ('HIGH')
self.higher.setAlignment (QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
_labelLayout.addWidget (self.higher)
# Slider
_grid.addWidget (QtGui.QLabel (''), 1, 0)
self.sliderBarLayout = QtGui.QHBoxLayout ()
self.sliderBarLayout.setSpacing (0)
_grid.addLayout (self.sliderBarLayout, 1, 1)
self.sliderBarLayout.addWidget (self.leftEndstop)
self.slider = QtGui.QSlider (QtCore.Qt.Horizontal)
self.slider.setTickPosition (QtGui.QSlider.TicksBelow)
self.slider.setTracking (True)
self.slider.setMinimumWidth (40)
self.slider.setPageStep (1)
self.sliderBarLayout.addWidget (self.slider)
self.rightEndstop = RightEndstop (self, self.root)
self.sliderBarLayout.addWidget (self.rightEndstop)
import sys, time
from PyQt4 import QtGui, QtCore
class TimeSlider (QtGui.QVBoxLayout):
def __init__ (self):
QtGui.QVBoxLayout.__init__ (self)
# Put everything in a grid
_manLayout = QtGui.QVBoxLayout ()
self._frame = QtGui.QFrame();
_manLayout.addWidget(self._frame)
_grid = QtGui.QGridLayout (self._frame)
# Slider limit labels
_grid.addWidget (QtGui.QLabel (''), 0, 0)
_labelLayout = QtGui.QHBoxLayout ()
_grid.addLayout (_labelLayout, 0, 1)
self.lower = QtGui.QLabel ('LOW')
_labelLayout.addWidget (self.lower)
self.higher = QtGui.QLabel ('HIGH')
self.higher.setAlignment (QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
_labelLayout.addWidget (self.higher)
# Slider
_grid.addWidget (QtGui.QLabel (''), 1, 0)
self.sliderBarLayout = QtGui.QHBoxLayout ()
self.sliderBarLayout.setSpacing (0)
_grid.addLayout (self.sliderBarLayout, 1, 1)
# self.sliderBarLayout.addWidget (self.leftEndstop)
self.slider = QtGui.QSlider (QtCore.Qt.Horizontal)
self.slider.setTickPosition (QtGui.QSlider.TicksBelow)
self.slider.setTracking (True)
self.slider.setMinimumWidth (40)
self.slider.setPageStep (1)
self.sliderBarLayout.addWidget (self.slider)
self._frame.setLayout(_grid)
self.addLayout (_manLayout)
#self.rightEndstop = RightEndstop (self, self.root)
# self.sliderBarLayout.addWidget (self.rightEndstop)
def show(self):
self._frame.show()
def hide(self):
self._frame.hide()
def isHidden(self):
return self._frame.isHidden()
class NewTimeSliderTest(QtGui.QWidget):
def __init__(self, parent=None, total=20):
super(NewTimeSliderTest, self).__init__(parent)
self.newTimeSlider = TimeSlider()
self.resize(841, 474)
self.newTimeSlider.hide()
self.button = QtGui.QPushButton('Show/Hide')
self.button.clicked.connect(self.handleButton)
main_layout = QtGui.QGridLayout()
main_layout.addWidget(self.button, 0, 0)
main_layout.addLayout(self.newTimeSlider, 0, 1)
self.setLayout(main_layout)
self.setWindowTitle('Test')
self._active = False
def handleButton(self):
#self.newTimeSlider.show()
isHidden = self.newTimeSlider.isHidden()
if isHidden:
self.newTimeSlider.show()
else:
self.newTimeSlider.hide()
app = QtGui.QApplication(sys.argv)
bar = NewTimeSliderTest(total=101)
bar.show()
sys.exit(app.exec_())
How about this ?
Any time you can all like this.
self.newTimeSlider.show()
or
self.newTimeSlider.hide()