Python, Tkinter, Can not access StringVar() Object - python-2.7

with the attached code i try to access the StringVar object in the widget object himself.
But unfortunately it says 'AttributeError: 'str' object has no attribute 'set''
Any idea why? Thanks in advance..
import Tkinter as tk
class mainWindow:
def __init__(self, master):
self.master = master
self.fieldList = {}
f = tk.Entry(self.master, text='', width = 7)
f.grid(column=0, row=0)
self.addToFieldList(f, 'MyFieldA')
def addToFieldList(self, fieldObj, fieldId):
fieldObj.bind('<Return>', lambda event, temp=fieldObj :self.commitField(event, temp))
t = tk.StringVar()
fieldObj['textvariable'] = t
setattr(fieldObj, 'fieldId', fieldId)
self.fieldList[fieldId] = fieldObj
def commitField(self, event, sender):
newValue = sender.get()
t = sender['textvariable']
t.set('newValue') # here comes the error
def main():
root = tk.Tk()
app = mainWindow(root)
root.wm_geometry("500x180")
root.mainloop()
if __name__ == '__main__':
main()

Put self in front of the StringVar which will let you call it without an error. This is because it is not a global variable and so the function cannot access it. Also change t = sender['textvariable'] to sender['textvariable'] = t.

Related

How to get the selected item in matching items of the list view using with pyqt4

Here is my sample code.I am learning the list view methods,I already posted one question,but i have a small doubt in my program.In my program after "fliter" i am getting the matched items of the word in that i want to choose the selected item using the enter key but it is printing the first item after selecting..I don't want to print the first item of the matched list..can any one please help me.Thank you in advance.
given below is my code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent=parent)
vLayout = QVBoxLayout(self)
hLayout = QHBoxLayout()
self.lineEdit = QLineEdit(self)
hLayout.addWidget(self.lineEdit)
self.filter = QPushButton("filter", self)
hLayout.addWidget(self.filter)
self.filter.clicked.connect(self.filterClicked)
self.list = QListView(self)
vLayout.addLayout(hLayout)
vLayout.addWidget(self.list)
self.model = QStandardItemModel(self.list)
codes = [
'windows',
'windows xp',
'windows7',
'hai',
'habit',
'hack',
'good'
]
for code in codes:
item = QStandardItem(code)
self.model.appendRow(item)
self.list.setModel(self.model)
shorcut=QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return), self)
shorcut.activated.connect(self.on_enter_pressed)
#QtCore.pyqtSlot()
def on_enter_pressed(self):
if len(self.lineEdit.text())>0:
self.filterClicked()
def filterClicked(self):
filter_text = str(self.lineEdit.text()).lower()
for row in range(self.model.rowCount()):
if filter_text in str(self.model.item(row).text()).lower():
self.list.setRowHidden(row, False)
self.list.setFocus()
else:
self.list.setRowHidden(row, True)
ix = self.list.selectionModel().selectedIndexes()
#here if i mentioned self.list.selectionModel().currentIndex() means it is automatically printing the first item in List_View
# i dont want to print first item ...after slecting the item in list view i will press enter key then only i want to print the selected item name
print ix.data()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
finally i got this answer..thq eyllanesc sir,i refer all your previous answers related to list view..Thank you so much..
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent=parent)
vLayout = QVBoxLayout(self)
hLayout = QHBoxLayout()
self.lineEdit = QLineEdit(self)
hLayout.addWidget(self.lineEdit)
self.filter = QPushButton("filter", self)
hLayout.addWidget(self.filter)
self.filter.clicked.connect(self.filterClicked)
self.list = QListView(self)
vLayout.addLayout(hLayout)
vLayout.addWidget(self.list)
self.model = QStandardItemModel(self.list)
codes = [
'windows',
'windows xp',
'windows7',
'hai',
'habit',
'hack',
'good'
]
for code in codes:
item = QStandardItem(code)
self.model.appendRow(item)
self.list.setModel(self.model)
shorcut=QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return), self)
shorcut.activated.connect(self.on_enter_pressed)
#QtCore.pyqtSlot()
def on_enter_pressed(self):
if len(self.lineEdit.text())>0:
self.filterClicked()
def filterClicked(self):
filter_text = str(self.lineEdit.text()).lower()
for row in range(self.model.rowCount()):
if filter_text in str(self.model.item(row).text()).lower():
self.list.setRowHidden(row, False)
self.list.setFocus()
else:
self.list.setRowHidden(row, True)
indexes = self.list.selectionModel().selectedIndexes()
for index in indexes:
print index.data().toString()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())

How to get the selection item in list view using pyqt4

Here is my sample code. When I click the index item in list view, I am getting the selection item,it's working fine.But I want to get the selected item using up and down arrows. Can anyone please help me. Thank you in advance.
Given below is my code:
import sys
from PyQt4 import QtCore,QtGui
class mtable(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.auto_search1 = QtGui.QWidget()
self.auto_search_vbox1 = QtGui.QVBoxLayout(self.auto_search1)
self.auto_search_vbox1.setAlignment(QtCore.Qt.AlignLeft)
hbox1=QtGui.QHBoxLayout()
self.le_search1 = QtGui.QLineEdit()
self.se_btn1 = QtGui.QPushButton("Search")
self.searchBtn = QtGui.QPushButton("Close")
self.searchBtn.clicked.connect(self.auto_search1.close)
self.se_btn1.clicked.connect(self.filterClicked1)
hbox1.addWidget(self.le_search1)
hbox1.addWidget(self.se_btn1)
hbox1.addWidget(self.searchBtn)
self.auto_search_vbox1.addLayout(hbox1)
self.total_list1 =[]
self.list1 = QtGui.QListView()
self.list1.clicked.connect(self.on_treeView_clicked)
self.model1 = QtGui.QStandardItemModel(self.list1)
self.y =['one','two', 'three']
for i in self.y:
self.total_list1.append(i)
for code in self.total_list1:
item1 = QtGui.QStandardItem(code)
self.model1.appendRow(item1)
self.list1.setModel(self.model1)
self.auto_search_vbox1.addWidget(self.list1)
self.auto_search1.show()
self.auto_search1.resize(1000,500)
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
itms = self.list1.selectedIndexes()
for data in itms:
print index.data().toString()
self.le_search1.setText(index.data().toString())
self.filterClicked1()
def filterClicked1(self):
print "searching logic"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
tb = mtable()
sys.exit(app.exec_())
Here I need to select the green highlighted item using arrow keys without clicking the item
You have to use the currentChanged signal of the selectionModel() of the QListView:
import sys
from PyQt4 import QtCore,QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.lineedit = QtGui.QLineEdit()
self.search_button = QtGui.QPushButton("Search")
self.close_button = QtGui.QPushButton("Close")
self.listview = QtGui.QListView()
model = QtGui.QStandardItemModel(self.listview)
for e in ('one', 'two', 'three'):
model.appendRow(QtGui.QStandardItem(e))
self.listview.setModel(model)
# signals connections
self.listview.selectionModel().currentChanged.connect(self.on_currentChanged)
QtCore.QTimer.singleShot(0, self.selectFirstItem)
# layout
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vlay = QtGui.QVBoxLayout(central_widget)
hlay = QtGui.QHBoxLayout()
hlay.addWidget(self.lineedit)
hlay.addWidget(self.search_button)
hlay.addWidget(self.close_button)
vlay.addLayout(hlay)
vlay.addWidget(self.listview)
self.resize(640, 480)
def selectFirstItem(self):
self.listview.setFocus()
ix = self.listview.model().index(0, 0)
self.listview.selectionModel().setCurrentIndex(ix, QtGui.QItemSelectionModel.Select)
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_currentChanged(self, current):
self.lineedit.setText(current.data())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Python Tkinter: Update entry field from another class

I have a Python Tkinter GUI class as following:
import Tkinter as tk
class AppClient(tk.Frame):
def __init__(self, master):
error_class = ErrorClass()
self.val_error_code = error_class.error_message
tk.Frame.__init__(self, master)
self.pack()
##Frame for error message display
error_frame = tk.Frame(self, highlightbackground="violet", highlightcolor="violet", highlightthickness=1, width=600, height = 60, bd= 0)
error_frame.pack(padx = 10, pady = 5, anchor = 'w')
## error code: Label and Entry
tk.Label(error_frame, text = 'Error message').grid(row = 0, column = 0, sticky = 'w')
self.error_code = tk.Entry(error_frame, background = 'white', width = 27)
self.error_code.grid(row = 0, column = 1, sticky = 'w', padx = 5, pady = 5)
def update_error_messsage(self):
self.error_code.delete(0, 'end')
self.error_code.insert(0, self.val_error_code)
if __name__ == '__main__':
root = tk.Tk()
app_client = AppClient(root)
app_client.mainloop()
I want to update the entry field error_code dynamically by using the function update_error_message. The problem is, error message is continuously updated from another class ErrorClass() and I am receiving the error message to my AppClient class by variable error_message.
How can I update the error_code entry filed whenever the value of the variable error_message got updated in another class (ErrorClass())
The simple solution is that you need a reference to your instance of AppClient inside of ErrorClass, and then allow the instance of ErrorClass to pass the new value to the app
For example:
class AppClient(tk.Frame):
def __init__(self, master):
error_class = ErrorClass(self)
...
def update_error_messsage(self, error_code):
self.error_code.delete(0, 'end')
self.error_code.insert(0, error_code)
class ErrorClass():
def __init__(self, app):
self.app = app
def update_error(self):
...
error_code = 42
self.app.update_error_message(error_code)

Not able to Dynamical Update Kivy Label Text

I am trying to add rows to a table like GUI.
These rows are to be a list of labels.
Each row that is updated has the following methods in that class:
AddRow - To add the list of strings that will be the text in that
label.
AddLabel - Adds a label to that row and appends the Label list
AddLabelRow - Creates the list Row in the actual table and
initializes the text to "empty"
ChangeLableText - Takes an input list of strings and changes the string in the label for that class.
I then have initialized a list of objects ContentList[] for this class and call the methods
But no matter which object's ChangeLabelText is called, only the text for ContentList[0] is updated.
import json
import requests
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.app import runTouchApp
class AddContent(GridLayout):
#response = requests.get("http://localhost:10010/")
# Get the response data as a python object. Verify that it's a dictionary.
#data = response.json()[3]
#Column_keys = ["country", "date", "answered_calls", "total_calls", "asr", "mou", "aou"]
RowList = []
Label_List = []
size = 0
def AddRow(self, InputList):
self.RowList = InputList
self.size = len(InputList)
def AddLabel(self,LayoutObj):
lbl = Label(size_hint_y = None, height = 30)
LayoutObj.add_widget(lbl)
return lbl
def AddLabelRow(self,LayoutObj):
for i in range(self.size):
Lbl = self.AddLabel(LayoutObj)
Lbl.text = "empty"
#self.Label_List[i].text = data[Column_keys[i]]
#Lbl.text = str(self.data[self.Column_keys[i]])
self.Label_List.append(Lbl)
def ChangeLabel_ListText(self, TextList):
for i in range(self.size):
#self.Label_List[i].text = data[Column_keys[i]] #data is fetched from Db
self.Label_List[i].text = TextList[i]
class TableView(GridLayout):
Col_Names = ["Date","Vendor","Country","MOU","ASR","AOU"]
ContentList = [AddContent(),AddContent(),AddContent()]
def __init__(self,**kwargs):
self.layout = GridLayout(cols = len(self.Col_Names), padding =5)
self.layout.bind(minimum_height=self.layout.setter('height'))
for i in range(len(self.Col_Names)):
btn = Button(text=self.Col_Names[i], size_hint_y=None, height=30)
self.layout.add_widget(btn)
self.ContentList[0].AddRow(['1sample1','1sample2','1sample3','1sample4','1sample5','1sample6'])
self.ContentList[1].AddRow(['2sample1','2sample2','2sample3','2sample4','2sample5','2sample6'])
self.ContentList[2].AddRow(['3sample1','3sample2','3sample3','3sample4','3sample5','3sample6'])
for i in range(3):
self.ContentList[i].AddLabelRow(self.layout)
self.ContentList[2].ChangeLabel_ListText(['a','b','c','d','e','f'])
if __name__ == '__main__':
Table = TableView()
runTouchApp(Table.layout)
The line self.ContentList[2].ChangeLabel_ListText(['a','b','c','d','e','f'])
updates only the first row whatever number is given for the index.
I have been breaking my head over this for the past week. I had initially done this with only one class instead of two which gave the same output.
Any help will help greatly. Thanks!
Your first problem is that RowList, Label_List, and size are class attributes in your code. But you want to set them in every instance individually. Solution: initialize these attributes inside the __init__ method like this:
def __init__(self, **kwargs):
super(AddContent, self).__init__(**kwargs)
self.RowList = []
self.Label_List = []
self.size = 0
The second problem is, that the GridLayout (which your class is subclassing) also contains an attribute called size. Solution: pick a different name for this attribute like so:
self.length = 0
If you now do
self.ContentList[i].ChangeLabel_ListText(['a','b','c','d','e','f'])
your i-th ContentList-entry will be changed.
Here is the complete solution:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.app import runTouchApp
class AddContent(GridLayout):
#response = requests.get("http://localhost:10010/")
# Get the response data as a python object. Verify that it's a dictionary.
#data = response.json()[3]
#Column_keys = ["country", "date", "answered_calls", "total_calls", "asr", "mou", "aou"]
def __init__(self, **kwargs):
super(AddContent, self).__init__(**kwargs)
self.RowList = []
self.Label_List = []
self.length = 0
def AddRow(self, InputList):
self.RowList = InputList
self.length = len(InputList)
def AddLabel(self,LayoutObj):
lbl = Label(size_hint_y=None, height=30)
LayoutObj.add_widget(lbl)
return lbl
def AddLabelRow(self,LayoutObj):
for i in range(self.length):
Lbl = self.AddLabel(LayoutObj)
Lbl.text = "empty"
#self.Label_List[i].text = data[Column_keys[i]]
#Lbl.text = str(self.data[self.Column_keys[i]])
self.Label_List.append(Lbl)
def ChangeLabel_ListText(self, TextList):
for i in range(self.length):
#self.Label_List[i].text = data[Column_keys[i]] #data is fetched from Db
self.Label_List[i].text = TextList[i]
class TableView(GridLayout):
Col_Names = ["Date","Vendor","Country","MOU","ASR","AOU"]
ContentList = [AddContent(),AddContent(),AddContent()]
def __init__(self,**kwargs):
self.layout = GridLayout(cols = len(self.Col_Names), padding=5)
self.layout.bind(minimum_height=self.layout.setter('height'))
for i in range(len(self.Col_Names)):
btn = Button(text=self.Col_Names[i], size_hint_y=None, height=30)
self.layout.add_widget(btn)
self.ContentList[0].AddRow(['1sample1','1sample2','1sample3','1sample4','1sample5','1sample6'])
self.ContentList[1].AddRow(['2sample1','2sample2','2sample3','2sample4','2sample5','2sample6'])
self.ContentList[2].AddRow(['3sample1','3sample2','3sample3','3sample4','3sample5','3sample6'])
for i in range(3):
self.ContentList[i].AddLabelRow(self.layout)
self.ContentList[2].ChangeLabel_ListText(['a','b','c','d','e','f'])
if __name__ == '__main__':
Table = TableView()
runTouchApp(Table.layout)

Tkinter Instance has no attributes

I am having an error against an innocent wish to play an audio in audio player using Tkinter. Error is:
Traceback (most recent call last):
File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 43, in
<module>
app = GUI(playerobj)
File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 10, in
__init__
self.create_button_frame()
AttributeError: GUI instance has no attribute 'create_button_frame'
My Code main_gui.py is:
from Tkinter import *
import tkFileDialog
import player
class GUI:
def __init__(self, player):
self.player = player
player.parent = player
self.root = Tk()
self.create_button_frame()
self.create_bottom_frame()
self.root.mainloop()
def create_button_frame(self):
buttonframe = Frame(self.root)
self.playicon = PhotoImage(file='../icons/play.gif')
self.stopicon = PhotoImage(file='../icons/stop.gif')
self.playbtn=Button(buttonframe, text ='play', image=self.playicon,
borderwidth=0, command=self.toggle_play_pause)
self.playbtn.image = self.playicon
self.playbtn.grid(row=3, column=3)
buttonframe.grid(row=1, pady=4, padx=5)
def create_bottom_frame(self):
bottomframe = Frame(self.root)
add_fileicon = PhotoImage(file='../icons/add_file.gif')
add_filebtn = Button(bottomframe, image=add_fileicon, borderwidth=0,
text='Add File', command = self.add_file)
add_filebtn.image = add_fileicon
add_filebtn.grid(row=2, column=1)
bottomframe.grid(row=2, sticky='w', padx=5)
def toggle_play_pause(self):
if self.playbtn['text'] == 'play':
self.playbtn.config(text='stop', image=self.stopicon)
self.player.start_play_thread()
elif self.playbtn['text'] == 'stop':
self.playbtn.config(text = 'play', image=self.playicon)
self.player.pause()
def add_file(self):
tfile = tkFileDialog.askopenfilename(filetypes = [('All supported',
'.mp3 .wav .ogg'), ('All files', '*.*')])
self.currentTrack = tfile
if __name__=='__main__':
playerobj = player.Player()
app = GUI(playerobj)
My Player button functions in another (as they have nothing to do with error)are:
import pyglet
from threading import Thread
class Player():
parent = None
def play_media(self):
try:
self.myplayer=pyglet.media.Player()
self.source = pyglet.media.load(self.parent.currentTrack)
self.myplayer.queue(self.source)
self.myplayer.queue(self.source)
self.myplayer.play()
pyglet.app.run()
except:
pass
def start_play_thread(self):
player_thread = Thread(target=self.play_media)
player_thread.start()
def pause(self):
try:
self.myplayer.pause()
self.paused = True
except: pass
Please help.
Seems like your problem is indentation. Your create_button_frame() function is not an attribute of the class GUI, it is a global function. Indent all the functions taking parameter self four spaces to the right. Then they will be methods of your class GUI.