Linenumber Widget with Notebook widget python ttk - python-3.x

I am using python 3.4.4 and tkinter ttk..currently trying to implement line number widget with my ttk notebook widget but not giving me error neither printing line number..its working fine with single Text widget... I surely made a mistake but I am not able to fix it thanks for helping me.
main.py
import tkinter.ttk as ttks
from tkinter import LEFT,RIGHT,X,Y,BOTH
class MainUI:
def __init__(self,master):
self.master = master
self.txs = []
self.linenumber = ttks.tkinter.Canvas(self.master,border=0,width=25,bg="#808b96")
self.linenumber.pack(side=LEFT,fill=Y)
self.nb = ttks.Notebook(self.master)
self.nb.pack(fill='both',expand=1)
self.add_tabs()
self._orig = self.txs[self.nb.index('current')]._w +"_orig"
self.master.call("rename",self.txs[self.nb.index('current')]._w,self._orig)
self.master.createcommand(self.txs[self.nb.index('current')]._w,self._proxy)
self.master.bind('<Control-n>',self.add_tabs)
def add_tabs(self,event=None):
self.page_name = ttks.Frame(self.nb)
self.tx = ttks.tkinter.Text(self.page_name)
self.txs.append(self.tx)
self.tx.pack(fill=BOTH,expand=1)
self.nb.add(self.page_name,text="pagename")
def redraw(self):
self.linenumber.delete("all")
i = self.txs[self.nb.index('current')].index("#0,0")
while True:
dline = self.txs[self.nb.index('current')].dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.linenumber.create_text(2,y,anchor="nw",text=linenum)
i = self.txs[self.nb.index('current')].index("%s+1line"%i)
def _proxy(self,*args):
try:
cmd = (self._orig,)+args
result = self.master.call(cmd)
if (args[0] in ("insert","replace","delete") or
args[0:3] in ("mark","set","insert") or
args[0:2] in ("xview","moveto") or
args[0:2] in ("xview","scroll") or
args[0:2] in ("yview","moveto") or
args[0:2] in ("yview","scroll")
):
self.txs[self.nb.index('current')].event_generate("<<Change>>",when="tail")
return result
except:
pass
def Onchange(self,event):
self.redraw()

I forgot to Bind Onchange method.
self.txs[self.nb.index('current')].bind("<<Change>>",self.Onchange)
self.txs[self.nb.index('current')].bind("<Configure>",self.Onchange)

Related

NameError: name 'Acte_D ' is not defined

I am currently developing a program to try an xml file. However I encounter a problem that has been blocking me for a few days now and I can rack my brains my beginner level in python and my many research does not help me to get over it.
I first try to retrieve 1 element from my xml file. I can do it well only the graphics window that should normally display it does not generate and I have the following error message:
The error :
window.fenetre_text(Acte_D) NameError: name 'Acte_D' is not defined`
well my code is :
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from xml.dom import minidom`
global file
global Acte_D
global element_A
global lines
class fenetreM(Tk):
#GUI
def __init__(self, master=None,*args, **kwargs):
Tk.__init__(self,master, *args, **kwargs)
self.menu_bar()
self.title("EssaiV1.0.1")
self.geometry("800x400")
self.minsize(380,140)
self.config(background='#F0F0F2')
#New_frame=Frame(fenetreM, bg='#abd7f4')`
def menu_bar(self):
menu_bar = Menu(self)
menu_file = Menu(menu_bar, tearoff=0)
menu_file.add_command(label="Open", underline=0, command=self.open_file)
menu_file.add_command(label="Affichage",underline=0,command=self.do_something)
menu_file.add_separator()
menu_file.add_command(label="Exit",underline=1,command=self.quit)
menu_bar.add_cascade(label="File",underline=0, menu=menu_file)
menu_help = Menu(menu_bar, tearoff=0)
menu_help.add_command(label="About", command=self.do_about)
menu_bar.add_cascade(label="Help",underline=0, menu=menu_help)
self.config(menu=menu_bar)
valid = False
return(valid)
def open_file(self):
types = [("All Files",".*")]
file = askopenfilename(title="File to open : ", filetypes=types)
print("Copy")
doc = minidom.parse(file)
print(doc.nodeName)
print(doc.firstChild.tagName)
Acte_D = doc.getElementsByTagName("ActeDescription")
print("\n")
element_A = (f" we have {Acte_D.length} element \n Version : ")
for i in Acte_D:
screen_1=(i.getAttribute("version"))
print(screen_1)
print("\n")
return (Acte_D)
def fenetre_text(self,Acte_D):
tk=Text(fenetreM, height = 10, width =100)
Fenetre_A=tk.inset(END,textvariable=self.element_A+Acte_D)
Fenetre_A.pack(side="top", fill="x", expand=True)
return(Acte_D)
window = fenetreM()
window.fenetre_text(Acte_D)
window.mainloop()
Can someone explain my mistake to me?
Thanks
I tried to graphically display the result of Acte_D in my window defined in my method fenetre_text.
But I can't.

PySide2: How to re-implement QFormLayout.takeRow()?

I've noticed that QFormLayout in Pyside2 does not have the takeRow method like its PyQt5 counterpart. I've attempted to subclass QFormLayout to incorporate a similar method, but I've run into Runtime Errors, as the removal behavor of the LabelRole item is different than the FieldRole item. Another issue being that the LabelRole item does not actually get taken off the row even when the row itself is removed.
The following is the test sample I've been working with using Python 3.8.6:
from PySide2.QtWidgets import *
import sys
class MyFormLayout(QFormLayout):
def __init__(self, *args, **kwargs):
super(MyFormLayout, self).__init__(*args, **kwargs)
self.cache = []
print(f"Formlayout's identity: {self=}\nwith parent {self.parent()=}")
def takeRow(self, row: int):
print(f"Called {self.takeRow.__name__}")
print(f"{self.rowCount()=}")
label_item = self.itemAt(row, QFormLayout.LabelRole)
field_item = self.itemAt(row, QFormLayout.FieldRole)
print(f"{label_item=}\n{field_item=}")
self.removeItem(label_item)
self.removeItem(field_item)
self.removeRow(row) ## <-- This seems necessary to make the rowCount() decrement. Alternative?
label_item.widget().setParent(None) ## <-- Runtime Error Here?
field_item.layout().setParent(None)
self.cache.append(label_item.widget(), field_item)
print(f"{self.rowCount()=}")
print(f"{self.cache=}")
print(self.cache[0])
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
return label_item, field_item
def restoreRow(self, insert_idx: int):
print(f"Called {self.restoreRow.__name__}")
print(f"{self.rowCount()=}")
print(f"{self.cache=}")
to_insert = self.cache.pop()
self.insertRow(insert_idx, to_insert[0], to_insert[1])
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
class MyWindow(QWidget):
def __init__(self):
super(MyWindow, self).__init__()
self.mainlay = MyFormLayout(self)
self.cmb = QComboBox()
self.cmb.addItems(["Placeholder", "Remove 1 and 2"])
self.cmb.currentTextChanged.connect(self.remove_rows_via_combo)
self.current_text = self.cmb.currentText()
self.hlay1, self.le1, self.btn1 = self.le_and_btn(placeholderText="1")
self.hlay2, self.le2, self.btn2 = self.le_and_btn(placeholderText="2")
self.hlay3, self.le3, self.btn3 = self.le_and_btn(placeholderText="3")
self.hlay4, self.le4, self.btn4 = self.le_and_btn(placeholderText="4")
self.remove_btn = QPushButton("Remove", clicked=self.remove_row_via_click)
self.restore_btn = QPushButton("Restore", clicked=self.restore_a_row_via_click)
self.mainlay.addRow("Combobox", self.cmb)
for ii, hlayout in zip(range(1, 5), [self.hlay1, self.hlay2, self.hlay3, self.hlay4]):
self.mainlay.addRow(f"Row {ii}", hlayout)
self.mainlay.addRow(self.remove_btn)
self.mainlay.addRow(self.restore_btn)
#staticmethod
def le_and_btn(**kwargs):
hlay, le, btn = QHBoxLayout(), QLineEdit(**kwargs), QPushButton()
hlay.addWidget(le)
hlay.addWidget(btn)
return hlay, le, btn
def remove_row_via_click(self):
self.mainlay.takeRow(1)
def restore_a_row_via_click(self):
self.mainlay.restoreRow(1)
def remove_rows_via_combo(self, text):
print(f"{self.remove_rows_via_combo.__name__} received the text: {text}")
if text == "Remove 1 and 2":
self.mainlay.takeRow(1)
self.mainlay.takeRow(1)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
I would like to understand why the behavior of the role items is different and how the method may be properly re-implemented.
The problem is that the label was created internally by Qt from a string, rather than by explicitly creating a QLabel in Python. This means that when the row is removed, the last remaining reference is also removed, which deletes the label on the C++ side. After that, all that's left on the Python side is an empty PyQt wrapper - so when you try to call setParent on it, a RuntimeError will be raised, because the underlying C++ part no longer exists.
Your example can therefore be fixed by getting python references to the label/field objects before the layout-item is removed:
class MyFormLayout(QFormLayout):
...
def takeRow(self, row: int):
print(f"Called {self.takeRow.__name__}")
print(f"{self.rowCount()=}")
label_item = self.itemAt(row, QFormLayout.LabelRole)
field_item = self.itemAt(row, QFormLayout.FieldRole)
print(f"{label_item=}\n{field_item=}")
# get refs before removal
label = label_item.widget()
field = field_item.layout() or field_item.widget()
self.removeItem(label_item)
self.removeItem(field_item)
self.removeRow(row)
label.setParent(None)
field.setParent(None)
self.cache.append((label, field))
print(f"{self.rowCount()=}")
print(f"{self.cache=}")
print(self.cache[0])
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
return label, field

How to thread with tkinter in python3 using queue?

I'm trying to thread definitions in tkinter using queue in specifically python3
I've had similar code in python2 work great using a similar method without queue but in python3 from what i've read tkinter doesn't allow for multithreading with gui. I found some examples that uses Queue process. They outline i'm suppose to create an Queue object, a new thread with access to that queue and check for input in the main thread
#!/usr/bin/python3
from tkinter import *
import time
import threading
import queue
import subprocess
def temp_sensor(queue_list):
warning = 0
while True:
var = "cat /sys/class/thermal/thermal_zone*/temp"
temp_control = subprocess.check_output([var], shell=True)
temp_length = len(temp_control)
temp_control = temp_control[35:]
temp_control = temp_control[:-4]
temp_control = int(temp_control)
degree_sign= u'\N{DEGREE SIGN}'
displayed_temp = "Tempature: " + str(temp_control) + degree_sign + "C"
if temp_control > 79:
warning = warning + 1
if warning == 3:
print ("Warning Core Tempature HOT!")
warning = 0
if temp_control > 90:
time.sleep(3)
print ("Warning EXTREMLY to HOT!!!")
queue_list.put(displayed_temp)
time.sleep(1)
class Gui(object):
def __init__(self, queue_list):
self.queue_list = queue_list
self.root = Tk()
self.root.geometry("485x100+750+475")
main_tempature_status = StringVar(self.root)
Ts = Entry(self.root, textvariable=main_tempature_status)
Ts.pack()
Ts.place(x=331, y=70, width=160, height=25)
Ts.config(state=DISABLED, disabledforeground="Black")
self.root.after(1000, self.read_queue)
def read_queue(self):
try:
temp = self.queue.get_nowait()
self.main_tempature_status.set(temp)
except queue_list.Empty:
pass
self.root.after(1000, self.read_queue)
if __name__ == "__main__":
queue_list = queue.Queue()
gui = Gui(queue_list)
t1 = threading.Thread(target=temp_sensor, args=(queue_list,))
t1.start()
gui.root.mainloop()
My desired result is to run a some of these definitions to do various tasks and display their variables in the tkinter entry using python3.
when i run my code it gives me the variable from the queue but it won't post to the GUI. please forgive my less then pythonic code.
Change you Gui class to this:
class Gui(object):
def __init__(self, queue_list):
self.queue_list = queue_list
self.root = Tk()
self.root.geometry("485x100+750+475")
self.main_tempature_status = StringVar(self.root)
self.Ts = Entry(self.root, textvariable=self.main_tempature_status)
self.Ts.pack()
self.Ts.place(x=331, y=70, width=160, height=25)
self.Ts.config(state=DISABLED, disabledforeground="Black")
self.root.after(1000, self.read_queue)
def read_queue(self):
try:
temp = self.queue_list.get_nowait()
self.Ts.config(state=NORMAL)
self.main_tempature_status.set(temp)
self.Ts.config(state=DISABLED)
except queue.Empty:
pass
self.root.after(1000, self.read_queue)
Explanation:
variable main_temperature_status is used in function read_queue as class variable, but not defined as class variable.
You cannot show the change in value of Entry widget if it is always disabled, so enabling it before value change in read_queue.

Drag and drop in QTreeView fails with items that hold a QImage

I have a list of items in a QTreeView. Each item holds a QImage object. If I try to drag and drop the item, the program freezes. But when I comment out the line objMod._Image = QImage(flags = Qt.AutoColor), the program runs fine.
How can I drag and drop the items with the QImage object? The QImage holds an image which is rendered. The rendering process takes a while, so it would be nice to keep the QImage object.
import sys
import os
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *
from PIL import Image, ImageCms, ImageQt
class ObjModel:
def __init__(self):
self._Image = None
class DragMoveTest(QMainWindow):
def __init__(self):
super(DragMoveTest,self).__init__()
self.initGUI()
self.show()
def initGUI(self):
self.treeView = QTreeView()
modelTreeView = QStandardItemModel()
self.treeView.setModel(modelTreeView)
for i in range(0, 4):
objMod = ObjModel()
objMod._Image = None
objMod._Image = QImage(flags = Qt.AutoColor)
item = QStandardItem('Test: %s' % str(i))
item.setData(objMod, Qt.UserRole + 1)
modelTreeView.invisibleRootItem().appendRow(item)
self.treeView.setDragDropMode(QAbstractItemView.InternalMove)
self.setCentralWidget(self.treeView)
def main(args):
app = QApplication(sys.argv)
qt_main_wnd = DragMoveTest()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main(sys.argv)
This is caused by a bug in PySide. During a drag and drop operation, the data in the dragged item must be serialized. This will be handled by Qt for most data-types, but for types that are specific to Python, special handling is required. This special handling seems to be broken in PySide. If your example is converted to PyQt, a TypeError is raised when trying to drag items, but the program does not freeze.
The source of the problem is that you are storing data using a custom Python class. PyQt uses pickle to serialize custom data-types, but it is not possible to also pickle the QImage that is stored in its __dict__, so the operation fails. I assume PySide must attempt something similar, but for some reason it does not raise an error when it fails. Qt grabs the mouse whilst dragging, so if the operation fails abnormally, it won't be released again, and the program will appear to freeze.
The simplest way to fix this is to avoid using a custom class to hold the QImage, and instead store the image directly in the item:
image = QImage()
item = QStandardItem('Test: %s' % i)
item.setData(image, Qt.UserRole + 1)
To store more data items, you can either use a different data-role for each one, or use a dict to hold them all:
data = {'image': QImage(), 'title': 'foo', 'timestamp': 1756790}
item.setData(data, Qt.UserRole + 1)
However, if you do this, you must always use string keys in the dict, otherwise you will face the same problems as before. (Using string keys means the dict can be converted into a QMap, which Qt knows how to serialize).
(NB: if you want to know whether a Qt class can be serialized, check the docs to see whether it defines the datastream operators).
I come up with a different solution. It is easier to have a object that holds a io.BytesIO. Your store the ImageData into the bytesIO variable. Upon on your image library you can open the image from the bytesIO variable.
In the demo the class ObjModel can handle QImage and Image from Pillow/PIL. If you use the set methods the image object will be converted into a bytesIO.
In short here a working example:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import io
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *
from PIL import Image, ImageCms, ImageQt
########################################################################
class ObjModel:
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self._ImageByteIO = None
#----------------------------------------------------------------------
def getObjByte(self):
""""""
return self._ImageByteIO
#----------------------------------------------------------------------
def getQImage(self):
""""""
try:
self._ImageByteIO.seek(0)
qImg = QImage.fromData(self._ImageByteIO.getvalue())
return qImg
except:
return None
#----------------------------------------------------------------------
def getPILImage(self):
""""""
try:
self._ImageByteIO.seek(0)
img = Image.open(tBytesIO)
return img
except:
return None
#----------------------------------------------------------------------
def setObjByte(self, fileName):
""""""
try:
tBytesIO = io.BytesIO()
f = open (fileName, 'rb')
tBytesIO.write(f.read())
f.close()
self._ImageByteIO = tBytesIO
except:
self._ImageByteIO = None
#----------------------------------------------------------------------
def setQImage(self, qImg):
""""""
try:
tBytesIO = io.BytesIO()
qByteArray = QByteArray()
qBuf = QBuffer(qByteArray)
qBuf.open(QIODevice.ReadWrite)
qImg.save(qBuf, 'PNG')
tBytesIO = io.BytesIO()
tBytesIO.write(qByteArray.data())
self._ImageByteIO = tBytesIO
except:
self._ImageByteIO = None
#----------------------------------------------------------------------
def setPILImage(self, pImg):
""""""
tBytesIO = io.BytesIO()
pImg.save(tBytesIO, 'png')
self._ImageByteIO = tBytesIO
#----------------------------------------------------------------------
class DragMoveTest(QMainWindow):
def __init__(self):
""""""
super(DragMoveTest,self).__init__()
self.initGUI()
self.show()
#----------------------------------------------------------------------
def initGUI(self):
""""""
self.treeView = QTreeView()
modelTreeView = QStandardItemModel()
self.treeView.setModel(modelTreeView)
for i in range(0, 4):
objMod = ObjModel()
objMod.setQImage(QImage(flags = Qt.AutoColor))
item = QStandardItem('Test: %s' % str(i))
item.setData(objMod, Qt.UserRole + 1)
modelTreeView.invisibleRootItem().appendRow(item)
self.treeView.setDragDropMode(QAbstractItemView.InternalMove)
self.setCentralWidget(self.treeView)
#----------------------------------------------------------------------
def main(args):
app = QApplication(sys.argv)
qt_main_wnd = DragMoveTest()
ret = app.exec_()
sys.exit(ret)
#----------------------------------------------------------------------
if __name__ == "__main__":
main(sys.argv)

'Close window' button wont work when using tkinter + gobject

My tkinter application runs fine, but to implement dbus functionality I had to use gobject. Got it working and all, except that, running both tkinter's and gobject's mainloops makes the "close window" button from the standard window manager ('x' button in the window interface) not to work. :/ Everything else works fine, including resizing, minimizing/maximizing, restoring, and moving the window.
Any help is appreciated,
Thanks,
Little code snippet:
import dbus
from dbus.service import Object
from dbus.mainloop.glib import DBusGMainLoop
class TBOPlayerDBusInterface (Object):
tboplayer_instance = None
def __init__(self, tboplayer_instance):
self.tboplayer_instance = tboplayer_instance
dbus_loop = DBusGMainLoop()
bus_name = dbus.service.BusName("org.tboplayer.TBOPlayer", bus = dbus.SessionBus(mainloop = dbus_loop))
Object.__init__(self, bus_name, "/org/tboplayer/TBOPlayer")
#dbus.service.method('org.tboplayer.TBOPlayer', in_signature = 'as')
def openFiles(self, files):
self.tboplayer_instance._add_files(files)
# ***************************************
# MAIN
# ***************************************
if __name__ == "__main__":
datestring=" 28 Fev 2017"
dbusif_tboplayer = None
try:
bus = dbus.SessionBus()
bus_object = bus.get_object("org.tboplayer.TBOPlayer", "/org/tboplayer>/TBOPlayer", introspect = False)
dbusif_tboplayer = dbus.Interface(bus_object, "org.tboplayer.TBOPlayer")
except Exception, e:
print e
if dbusif_tboplayer is None:
tk.CallWrapper = ExceptionCatcher
bplayer = TBOPlayer()
TBOPlayerDBusInterface(bplayer)
def refresh_player():
bplayer.root.update()
return True
def run_gobject():
gobject.MainLoop().run()
gobject.idle_add(refresh_player)
bplayer.root.after(100, run_gobject)
bplayer.root.mainloop()
else:
if len(sys.argv[1:]) > 0:
dbusif_tboplayer.openFiles(sys.argv[1:])
exit()
I found the problem. For some reason, using tkinter's and gobject's mainloops interferes with the behavior of the WM_DELETE_WINDOW event, which I was using for saving some data before closing the program. Solved the problem by binding to the Configure event instead. And now the main method is as follows:
if __name__ == "__main__":
datestring=" 28 Fev 2017"
dbusif_tboplayer = None
try:
bus = dbus.SessionBus()
bus_object = bus.get_object("org.tboplayer.TBOPlayer", "/org/tboplayer/TBOPlayer", introspect = False)
dbusif_tboplayer = dbus.Interface(bus_object, "org.tboplayer.TBOPlayer")
except Exception, e:
print e
if dbusif_tboplayer is None:
tk.CallWrapper = ExceptionCatcher
bplayer = TBOPlayer()
TBOPlayerDBusInterface(bplayer)
gobject_loop = gobject.MainLoop()
def refresh_player():
try:
bplayer.root.update()
return True
except Exception, e:
bplayer.quit_omx()
gobject_loop.quit()
def run_gobject():
gobject_loop.run()
gobject.idle_add(refresh_player)
bplayer.root.after(100, run_gobject)
bplayer.root.mainloop()
else:
if len(sys.argv[1:]) > 0:
dbusif_tboplayer.openFiles(sys.argv[1:])
exit()

Resources