I have 15 def's. I have 15 radiobuttons (p1,p2,p3.....p15). I have 1 QPush Button.
When i want to use my first def, i select "p1" click on my QPushButton and then use this def. Why i need it? because i need process texts, i open a text into my textedit and i need process it, but i want to use only one def using radiobutton.
How can i do it?
for example:
self.radioButton_1 = QRadioButton(self.Processing)
self.radioButton_1.setGeometry(QRect(520, 200, 50, 22))
self.radioButton_1.setObjectName(_fromUtf8("radioButton_1"))
self.radioButton_1.setText(QApplication.translate("Form", "P1", None, QApplication.UnicodeUTF8))
self.processLineButton = QPushButton(self.Processing)
self.processLineButton.setGeometry(QRect(800, 100, 100, 37))
self.processLineButton.setText(QApplication.translate("None","Process", None, QApplication.UnicodeUTF8))
and
def example(exampless):
example = []
for exx in exampless:
es = re.findall("\.{3}!", exx)
if es:
example = example + [exx]
#endif
#endfor
self.TextProcess.setPlainText(example)
First you'll need to find the checked radio button, then you can run the function assigned to that button, something like this:
for radioButton in self.findChildren(QtGui.QRadioButton):
if radioButton.isChecked():
radioButtonText = radioButton.text()
print "Radio Button Selected: ", radioButtonText
if radioButtonText == "example":
example(args)
Related
def move(sp, t):
if sp == "eightA":
sps = eightA
if t == "sixA":
st = sixA
if st == " ":
# target is empty
sps["text"] = " "
st["text"] = str(sps["text"])
Hello Everyone, Im trying to make this function to "move" text from a tkinter button to another, lets say sp is what i want to move, and t is the target so i want to move text
from the button eightA to sixA, also note that i want to be able to use this function on any 2 buttons, Its hard to explain, but please help if you can, the code above is one i tried out of alot other which didnt work,
Thanks
Procedure
Store the text on first button in a variable
Configure first button to have no text
Configure second button to have text stored in variable
Example
btn1 = tk.Button(text="Hello")
btn2 = tk.Button(text="Not Hello")
# store text on btn1 in a variable
txt = btn1['text']
# configure btn1 to have no text
btn1.config(text="")
# configure btn2 to have text stored in variable
btn2.config(text=txt)
So your function would look like
def move(btn1, btn2):
txt = btn1['text']
btn1.config(text=" ")
btn2.config(text=txt)
I'm trying to create a GUI, in the nav menu you can click a cascade option to open another window where you can click roll to generate a set of numbers. It comes up with error. I think it's because the function is called from another function I just don't know how to get that function to call it/ if there is any other ways to fix this. I've tried global functions and looking it up but haven't found anything other than using classes so far, which I don't know how to do.
line 147, in totalRolls
txtresultsOut.set(totalRollResults)
NameError: name 'txtresultsOut' is not defined
Here is the code that is relevant to it. I've called the function to skip having to input all the other code for the main gui window.
def rollSix():
s = 0
numbers = [0,0,0,0]
for i in range(1,5):
numbers[s] = randrange(1,7)
s += 1
numbers.remove(min(numbers))
Result = sum(numbers)
totalRollResults.append(Result)
def totalRolls():
rollOne()
rollTwo()
rollThree()
rollFour()
rollFive()
rollSix()
txtresultsOut.set(totalRollResults)
def rollw():
rollWindow = tix.Tk()
rollWindow.title("Dice Rolls")
diceLabel = Label(rollWindow, text = "Click Roll for your Stats")
diceLabel.grid(row = 0, column = 0)
rollBtn = Button(rollWindow, text = "Roll Stats", command = totalRolls)
rollBtn.grid(row = 1, column = 0)
txtresultsOut = StringVar()
resultsOut = Entry(rollWindow, state = "readonly", textvariable = txtresultsOut)
resultsOut.grid(row = 2, column = 0)
rollw()
first of all I would NOT recommend using StringVar(). You can use the .get() method of Entry to obtain the value inside the same. Try this way and make a global declaration of the Entry whose values you want to get in other functions.
EDIT------------
#you can use the following code to make your entry active to be edited.
entry.configure(state='normal')
# insert new values after deleting old ones (down below)
entry.delete(0,END)
entry.insert(0, text_should_be_here)
# and finally make its state readonly to not let the user mess with the entry
entry.configure(state='readonly')
So I'm grabbing links of events off a website and putting them into a drop down menu to be selected. My code for the menu:
import Tkinter as tk
from Tkinter import StringVar
selectMenu = tk.Tk()
# #-> this is what I have
# Followed by what you can use
#var = Vars()
#events = var.GetVars('Event')
events = " "
options = []
links = []
#forms = (driver.find_elements_by_class_name("with-cats")) #This is what I have
forms = ["Yolo ","Dad? Closed","Anotha One","Normies! Closed"] #This is so you can try it for yourself
for x in forms:
#info = x.text
info = x #Again, this is so you can try it for yourself
if events in info.lower():
links.append(x)
for link in range(0,len(links)):
#options.append(links[link].text)
options.append(links[link])
list(set(options))
selection = []
for link in range(0,len(options)):
selection.append(options[link])
select = StringVar(selectMenu)
select.set("--None Selected--")
menu = tk.OptionMenu(selectMenu, select, *(selection))
msg = "Which one would you like to attend?"
label = tk.Label(selectMenu, text=msg, font="Helvedica 14")
label.pack(side='top', pady=10)
menu.pack(side="top", pady=10)
selectMenu.attributes('-topmost', True)
selectMenu.mainloop()
So this works fine and dandy, but I would like to improve the look to make it more obvious which events are open. To clarify, an event found that is open and put into the menu may look like "This is a cool event", but one that is closed would be read as "This is a cool event Closed". My aim is to be able to make the foreground red of either just the word Closed or the string containing Closed, whichever is possible if any (And I'm not sure if it's possible because menus and buttons on osx are usually defaulted to system settings, maybe there is a way around this?).
Current: Desired:
According to the documentation for OptionMenu here and here I don't think there is a way to set the color of text.
You might be able to get something close to what you want by using a listBox instead. See post here for the listBox example.
Found a solution! Using a Menu inside of a MenuButton the same way Tkinter creates MenuOptions, I was able to create a custom MenuOption. If you want to add more options, you can use the menbutton.configure() option to edit the button, and menbutton.menu to edit the menu items.
import Tkinter as tk
from Tkinter import Menu, Menubutton
class Vars():
global vari
vari = {}
def GetVars(self, var):
return vari.get(str(var))
def SendVars(self, var, val):
vari[str(var)] = val
class App():
def buttselect(self, link, menbutton, selectMenu):
var = Vars()
var.SendVars("Selection", link) # Store selected event
menbutton.configure(text=link) # Set menu text to the selected event
def prnt(self, link):
var = Vars()
print var.GetVars("Selection") # Print event
def __init__(self, selectMenu):
events = " "
options = []
links = []
forms = ["Yolo ","Dad? Closed","Anotha One","Normies! Closed"] #This is so you can try it for yourself
menbutton = Menubutton (selectMenu, text="--None Selected--", relief="raised")
menbutton.grid()
menbutton.menu = Menu (menbutton, tearoff=0)
menbutton["menu"] = menbutton.menu
#Get a list of event names
for x in forms:
info = x #Again, this is so you can try it for yourself
#If desired event keyword is in an event name, add it to the correct links
if events in info.lower():
links.append(x)
#Remove duplicates
for link in range(0,len(links)):
options.append(links[link])
list(set(options))
#Final list of event names turned into menu commands
for link in options:
if "Closed" in link:
menbutton.menu.add_command( label= link, command= lambda link=link: self.buttselect(link, menbutton, selectMenu), foreground='red')
else:
menbutton.menu.add_command( label= link, command= lambda link=link: self.buttselect(link, menbutton, selectMenu))
b = tk.Button(selectMenu, text="Selection", command= lambda link=link: self.prnt(link)) #Print selected event
b.pack()
msg = "Which one would you like to attend?"
label = tk.Label(selectMenu, text=msg, font="Helvedica 14")
label.pack(side='top', pady=10)
menbutton.pack(side="top", pady=10)
selectMenu = tk.Tk()
selectMenu.attributes('-topmost', True)
app = App(selectMenu)
selectMenu.mainloop()
This results in exactly the result desired:
I found a way!
Let's say x is an optionmenu with options:
options=['Red','Blue','Green']
defopt=tk.StringVar(options[0]) #StringVariable to hold the selected option.
x=tk.OptionMenu(self.optmenuframe,defopt,*options)
Now, get the menu object from the optionmenu and use entryconfig method. That's it!
x.children['menu'].entryconfig(0,foreground='red')
x.children['menu'].entryconfig(1,foreground='blue')
x.children['menu'].entryconfig(2,foreground='green')
#0 is the index of the option you want to apply the configurations to.
I want to activate command link button if at least one element is checked in a treeview.
I tried this method but it is not working well :
def activate_launch_button(self):
model = self.scenarios.model()
checked_indexes = model.match(model.index(0, 0), QtCore.Qt.CheckStateRole,QtCore.Qt.Checked, -1,QtCore.Qt.MatchExactly | QtCore.Qt.MatchRecursive)
print checked_indexes
if checked_indexes != []:
self.launch_btn.setEnabled(True)
The problem with this method is the button is activated only after closing the window. I don't understand why.
For caling this method I put it in two methods :
def show(self):
self.project.load()
if self.project.tranus_project:
self.tranus_folder.setText(self.project.tranus_project.path)
self.activate_launch_button()
self.launch_options_TRANUS()
super(OptionsTRANUSDialog, self).show()
def select_tranus_folder(self):
folder = QtGui.QFileDialog.getExistingDirectory(self, "Select directory")
if folder:
self.tranus_folder.setText(folder)
if not self.project.load_tranus_folder(folder):
self.tranus_folder.setText('')
self.reload_scenarios()
self.activate_launch_button()
I really want that the command link button should be activated when at least one element of treeview is checked and to be inactive if there is no element checked.
Thanks.
Finally, I found solution to all my problems :
def activate_launch_button(self):
model = self.scenarios.model()
model.itemChanged.connect(self.check_configure)
def check_configure(self,item):
model = self.scenarios.model()
index = model.indexFromItem(item)
if index.data(QtCore.Qt.CheckStateRole) != index.data(QtCore.Qt.UserRole + QtCore.Qt.CheckStateRole):
if index.data(QtCore.Qt.CheckStateRole)!= QtCore.Qt.Unchecked :
self.count_check+=1
model.setData(index,index.data(QtCore.Qt.CheckStateRole),QtCore.Qt.UserRole + QtCore.Qt.CheckStateRole)
else :
self.count_check-=1
model.setData(index,index.data(QtCore.Qt.CheckStateRole),QtCore.Qt.UserRole + QtCore.Qt.CheckStateRole)
print self.count_check
self.launch_btn.setEnabled(self.count_check>0)
Finally, I found a partial solution to my problem, I used the signal itemChanged http://pyqt.sourceforge.net/Docs/PyQt4/qstandarditemmodel.html#itemChanged
def activate_launch_button(self):
model = self.scenarios.model()
model.itemChanged.connect(self.check_configure)
def check_configure(self):
self.launch_btn.setEnabled(True)
It activates the button when there is one element is checked however when I uncheck all, the button doesn't become inactive. How can I solve this issue ?
I have the following Python MFC code. I have a listbox which I fill with some values, and when the user clicks on the values I want the static text control to be updated with the current selection. There are two problems with this code. The first is that the value in the text control is only updated the first time I click on the listbox. The second is that the value lags behind the real selected value in the listbox, presumably because the control handles the click after my handler code gets called. I'd appreciate help with either of these issues.
An odd thing, (perhaps a clue) is that when I mouse-down over the 'OK' button but move away for mouse-up the static text does get updated as I would expect.
I've tried RedrawWindow(), UpdateWindow(), ShowWindow() on both the control and the dialog, and nothing seems to make any difference.
import win32con
from pywin.mfc import dialog
IDC_LIST = 9000
IDC_TEXT = 9001
class ChooserDialog(dialog.Dialog):
def __init__(self):
DIALOGTEMPLATE = [
["Test", (0, 0, 254, 199), win32con.WS_CAPTION | win32con.DS_MODALFRAME, None, (8, "MS SansSerif")],
[128, "OK", win32con.IDOK, (197,178,50,14), win32con.BS_PUSHBUTTON | win32con.WS_VISIBLE],
["listbox", "List", IDC_LIST, (7,7,177,186), win32con.WS_VISIBLE],
["static", "", IDC_TEXT, (197,7,50,160), win32con.WS_CHILD | win32con.WS_VISIBLE]
]
dialog.Dialog.__init__(self, DIALOGTEMPLATE)
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
for i in ["one", "two", "three"]:
self.GetDlgItem(IDC_LIST).AddString(i)
self.HookCommand(self.OnNotify, IDC_LIST)
return rc
def OnNotify(self, ctrl, action):
if ctrl == IDC_LIST:
selected = self.GetDlgItem(IDC_LIST).GetCurSel()
self.SetDlgItemText(IDC_TEXT, "%d" % selected)
self.GetDlgItem(IDC_TEXT).RedrawWindow()
return 1
dia = ChooserDialog()
dia.DoModal()
The first problem with the code was that the win32con.LBS_NOTIFY style wasn't set for the listbox control. If that isn't set you won't get any messages from the LB. The few messages that I was getting were due to other events in the dialog.
The second problem was that I was using HookCommand(), which intercepts commands, and allows you to handle them. Instead I wanted HookMessage() to get only the notifications. It seems notifications get called after the update of the control, so that's exactly what I wanted.
The LBN_SELCHANGE notification, according to MSDN documentation is received through the WM_COMMAND message. It seems I must subscribe to all WM_COMMAND messages in the dialog, and then filter them in my handler. The LBN_SELCHANGE documentation explains about what is passed, and in conjunction with the HookMessage() Python documentation you can work out how to handle it.
Here is the working code:
import win32con
from pywin.mfc import dialog
IDC_LIST = 9500
IDC_TEXT = 9501
class ChooserDialog(dialog.Dialog):
def __init__(self):
DIALOGTEMPLATE = [
["Test", (0, 0, 254, 199), win32con.WS_CAPTION | win32con.DS_MODALFRAME, None, (8, "MS SansSerif")],
[128, "OK", win32con.IDOK, (197,178,50,14), win32con.BS_PUSHBUTTON | win32con.WS_VISIBLE],
["listbox", "List", IDC_LIST, (7,7,177,186), win32con.WS_VISIBLE|win32con.LBS_NOTIFY],
["static", "", IDC_TEXT, (197,7,50,160), win32con.WS_CHILD | win32con.WS_VISIBLE]
]
dialog.Dialog.__init__(self, DIALOGTEMPLATE)
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
for i in ["one", "two", "three"]:
self.GetDlgItem(IDC_LIST).AddString(i)
self.HookMessage(self.OnNotifyCommand, win32con.WM_COMMAND)
return rc
def OnNotifyCommand(self, data):
msg_id = data[1] # should always be WM_COMMAND
wParam = data[2]
lParam = data[3]
list_id = wParam & 0xffff
notification_code = (wParam & 0xffff0000) >> 16
if list_id != IDC_LIST: return # not our list box.
if notification_code != win32con.LBN_SELCHANGE: return # Not a change of selection
selected = self.GetDlgItem(IDC_LIST).GetCurSel()
self.SetDlgItemText(IDC_TEXT, "%d"%selected)
dia = ChooserDialog()
dia.DoModal()