I am trying write somwthing like messenger with built-in stegonagraphy. Idea is simple: when I send a text it switch it to images, when find a specified pixel in my program. But I have a problem with multithreading mechanism. I worte two methods: receive and write. They are working with excahnging some different commands. Also receive is in separated thread, so I can listen forever. But commands, that should intercept send method are intercepted by recieve method and nothing is happen. My idea is to temporary pause "receive" until I send all, that I need. This is my code for client (server also have same methods):
Client's side code:
import socket
from tkinter import *
import tkinter.scrolledtext as scrolledtext
import threading
from tkinter import filedialog as fd
import time
HOST = '192.168.1.11' #my ip
PORT = 1234
SEPARATOR = '<SEPARATOR>'
BUFFER_SIZE = 1024
class Client:
def __init__(self, host, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.gui_done = False
self.running = True
self.gui_thread = threading.Thread(target=self.gui_loop)
self.receive_thread = threading.Thread(target=self.receive)
self.gui_thread.start()
self.receive_thread.start();
def gui_loop(self):
self.win = Tk()
self.win.title('Client 2')
self.win.configure(bg="lightgray")
self.chat_label = Label(self.win, text="Chat:", bg="lightgray")
self.chat_label.config(font=("Arial", 12))
self.chat_label.pack(padx=20, pady=5)
self.text_area = scrolledtext.ScrolledText(self.win)
self.text_area.pack(padx=20, pady=5)
self.text_area.config(state='disabled')
self.msg_label = Label(self.win, text="Message:", bg="lightgray")
self.msg_label.config(font=("Arial", 12))
self.msg_label.pack(padx=20, pady=5)
self.input_area = Text(self.win, height=5)
self.input_area.pack(padx=20, pady=5)
self.send_button = Button(self.win, text="Send", command=self.write)
self.send_button.config(font=("Arial", 12))
self.send_button.pack(padx=20, pady=5)
self.gui_done = True
self.win.protocol("WM_DELETE_WINDOW", self.stop)
self.win.mainloop()
def write(self):
self.receive_thread.pause();
for i in range(0,4):
#---------Send command---------
print('Connected...')
time.sleep(0.1);
self.sock.sendall('send'.encode());
#---------Read file------------
filename = (str(i+1) + '.jpg')
if i==3:
filename = 'end.jpg'
data = None
with open(filename, 'rb') as f:
data = f.read()
#--------Beginning sending process--------------
while True:
cmd = self.sock.recv(32).decode();
if cmd:
print(cmd);
#---------Receiving sendok-----
if cmd == "sendok":
self.sock.sendall('finfo'.encode());
temp = (str(filename) +'<SEPARATOR>' + '%16d' % len(data)).encode();
print(temp);
self.sock.sendall(temp);
#--------Receiving finfok------
if cmd == "finfok":
self.sock.sendall('img'.encode());
self.sock.sendall(data)
print('File transmission done.')
break
self.sock.sendall('end'.encode());
self.receive_thread.start(self.sock);
def stop(self):
self.running = False
self.win.destroy()
self.sock.close()
exit(0)
def receive(self):
while True:
print('[cmd] Waiting for command...')
command = self.sock.recv(32).decode()
if command:
print('[cmd] ' + command)
if command == 'send':
command = None
self.sock.sendall(b'sendok')
if command == 'finfo':
command = None
finfo = self.sock.recv(1024).decode()
print(finfo)
if SEPARATOR not in finfo:
self.sock.sendall(b'finfo_error')
break
else:
filename, filesize = finfo.split(SEPARATOR)
filesize = int(filesize)
self.sock.sendall(b'finfok')
if command == 'img':
command = None
print('[img] File name: ' + filename + ' | File size: ' + str(filesize) + '.')
file = open(filename, 'wb')
recvd = b''
while filesize > len(recvd):
data = self.sock.recv(BUFFER_SIZE)
if not data:
break
recvd += data
file.write(data)
print('[rcv] Received ' + str(len(recvd)) + '/' + str(filesize) + '.')
if command == 'end':
command = None
client = Client(HOST, PORT)
Server's code
from tkinter import *
from tkinter import scrolledtext
import threading
import socket
import time
HOST_IP = '192.168.1.11'
HOST_PORT = 1234
SEPARATOR = '<SEPARATOR>'
BUFFER_SIZE = 1024
NUMS_OF_CLIENT = 1
class Server:
def __init__(self, host, port):
self.gui_thread = threading.Thread(target=self.gui_loop)
self.gui_thread.start()
self.host = host
self.port = port
self.client_info = None
self.socket_client = None
self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket_server.bind((self.host, self.port))
self.socket_server.listen(NUMS_OF_CLIENT)
print('[*] Waiting for client to connect')
self.socket_client, self.client_info = self.socket_server.accept()
print('[+] Client (' + str(self.client_info[0]) + ') connected.')
self.receive_thread.start(self.socket_client);
self.gui_done = False
gui_thread = threading.Thread(target=self.gui_loop)
gui_thread.start()
self.running = True
def receive(self):
while True:
print('[cmd] Waiting for command...')
command = self.socket_client.recv(32).decode()
if command:
print('[cmd] ' + command)
if command == 'send':
command = None
self.socket_client.sendall(b'sendok')
if command == 'finfo':
command = None
finfo = self.socket_client.recv(1024).decode()
if SEPARATOR not in finfo:
self.socket_client.sendall(b'finfo_error')
break
else:
filename, filesize = finfo.split(SEPARATOR)
filesize = int(filesize)
self.socket_client.sendall(b'finfok')
if command == 'img':
command = None
print('[img] File name: ' + filename + ' | File size: ' + str(filesize) + '.')
file = open(filename, 'wb')
recvd = b''
while filesize > len(recvd):
data = self.socket_client.recv(BUFFER_SIZE)
if not data:
break
recvd += data
file.write(data)
print('[rcv] Received ' + str(len(recvd)) + '/' + str(filesize) + '.')
if command == 'end':
command = None
command = None
def send(self):
self.receive_thread.pause();
for i in range(6,10):
#---------Send command---------
print('Connected...')
time.sleep(0.1);
self.socket_client.sendall('send'.encode());
#---------Read file------------
filename = (str(i+1) + '.jpg')
if i==3:
filename = 'end.jpg'
data = None
with open(filename, 'rb') as f:
data = f.read()
#--------Beginning sending process--------------
while True:
cmd = self.socket_client.recv(32).decode();
if cmd:
print(cmd);
#---------Receiving sendok-----
if cmd == "sendok":
self.socket_client.sendall('finfo'.encode());
temp = (str(filename) +'<SEPARATOR>' + '%16d' % len(data)).encode();
print(temp);
self.socket_client.sendall(temp);
#--------Receiving finfok------
if cmd == "finfok":
self.socket_client.sendall('img'.encode());
self.socket_client.sendall(data)
print('File transmission done.')
break
self.sock.sendall('end'.encode());
self.receive_thread.start(self.sock);
def send_th(self):
send_thread = threading.Thread(target = self.send)
send_thread.start()
## self.receive_thread.
def exit(self):
print('[*] Disconnecting...')
try:
self.socket_client.close()
self.socket_server.close()
except:
self.socket_server.close()
finally:
print('[-] Disconnected111111.')
print('[-] Disconnected.')
def gui_loop(self):
self.win = Tk();
self.win.title("Client 1.0");
self.win.configure(bg="lightgray");
self.chat_label = Label(self.win, text="Chat:", bg="lightgray")
self.chat_label.config(font=("Arial", 12))
self.chat_label.grid(row = 0, column = 0, columnspan = 3)
self.text_area = scrolledtext.ScrolledText(self.win)
self.text_area.grid(row = 1, column = 0, columnspan = 3, rowspan = 5)
self.text_area.config(state='disabled')
self.msg_label = Label(self.win, text="Message:", bg="lightgray")
self.msg_label.config(font=("Arial", 12))
self.msg_label.grid(row = 6, column = 0, columnspan = 3)
self.input_area = Text(self.win, height=5)
self.input_area.grid(row = 7, column = 0, columnspan = 3)
self.start_button = Button(self.win, text="Host")
self.start_button.config(font=("Arial", 12))
self.start_button.grid(row = 8, column = 0)
self.send_button = Button(self.win, text="Send", command = self.send_th)
self.send_button.config(font=("Arial", 12))
self.send_button.grid(row = 8, column = 1)
self.exit_button = Button(self.win, text="Exit", command = self.exit)
self.exit_button.config(font=("Arial", 12))
self.exit_button.grid(row = 8, column = 2)
self.gui_done = True
self.win.protocol("WM_DELETE_WINDOW")
self.win.mainloop()
server = Server(HOST_IP, HOST_PORT)
I have a script in Maya (python) that renders a series of frames to the V-ray frame buffer, one for each render layer. It is working well, but when switching render layers and launching the next render, Maya grabs focus, interrupting whatever task the artist had moved on to while the script was running. I would like this to be a background task. Maya is running on Windows.
import maya
import maya.cmds as cmds
import re
from functools import partial
import sys
from datetime import datetime
global cancel
cancel = 0
print 'batch_review'
def no_cam_window_popup(no_cam_set_list):
#print no_cam_set_list
cmds.window(title = 'WARNING: NO CAMERAS LINKED TO LAYERS', width = 300, height = 75, sizeable = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = ("no cam set for layers:"))
for layer in no_cam_set_list:
cmds.text(label = ('' + layer + ', '),font = 'boldLabelFont')
cmds.showWindow()
def renderThumbs(checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld,*args):
global cancel
cams = cmds.ls(type = "camera")
cancel = 0
popup_win = 0
no_cam_set_list = []
cmds.loadPlugin('vrayformaya', quiet=True)
cmds.pluginInfo('vrayformaya', edit=True, autoload=True)
cmds.setAttr("defaultRenderGlobals.ren", "vray", type = "string")
curLay = cmds.editRenderLayerGlobals( currentRenderLayer = True, query = True )
changeLay = curLay
rls = cmds.ls(type = "renderLayer")
renCams = cmds.ls(type = "camera")
renCam = "persp"
lowBut = cmds.checkBox(checkBoxLow,value = True, query = True)
midBut = cmds.checkBox(checkBoxMid,value = True, query = True)
highBut = cmds.checkBox(checkBoxHigh,value = True, query = True)
globopt_cache_geom_plugins = cmds.getAttr('vraySettings.globopt_cache_geom_plugins')
#print 'globopt_cache_geom_plugins = ',globopt_cache_geom_plugins
print " "
print "-- batch_review --"
res = cmds.intField(intField_res, v = True, query = True)
thr = cmds.floatField(floatField_thrhld, v = True,query = True)
if lowBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if midBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if highBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
print "--- "
print " "
for rl in rls:
found_cam = 0
if rl != "defaultRenderLayer" and cancel == 0:
rlState = cmds.getAttr(rl + ".renderable")
if rlState == 1:
print ' '
print "rende layer = ",rl
cmds.editRenderLayerGlobals( currentRenderLayer = rl )
for cam in cams:
camState = cmds.getAttr(cam + ".renderable")
if camState == 1:
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
print 'using ' + cam + ' for ' + rl
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
print " "
found_cam = 1
if found_cam == 0:
print 'no camera link found, using persp cam for ',rl
cam = 'persp'
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
popup_win = 1
no_cam_set_list.append(rl)
#if popup_win == 1:
#no_cam_window_popup(no_cam_set_list)
def checkBoxCheckLow(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 800,edit = True)
cmds.floatField(floatField_thrhld, v = .1,edit = True )
cancel = 0
def checkBoxCheckMid(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 1000,edit = True)
cmds.floatField(floatField_thrhld, v = .5,edit = True )
cancel = 0
def checkBoxCheckHigh(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.intField(intField_res, v = 2000,edit = True)
cmds.floatField(floatField_thrhld, v = .008,edit = True )
cancel = 0
def checkBoxAOVchange(checkBoxAOV,*args):
checkBoxAOVval = cmds.checkBox(checkBoxAOV,value = True,query = True)
if checkBoxAOVval == 1:
cmds.setAttr("vraySettings.relements_enableall", 1)
if checkBoxAOVval == 0:
cmds.setAttr("vraySettings.relements_enableall", 0)
def rrCheckbox(checkBoxRenderRegion,reg,*args):
global gReg
zeroes = ['0','0','0','0']
tRes = cmds.vray("vfbControl","-getregion")
if tRes != zeroes:
gReg = tRes
rrstate = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
if rrstate == 0:
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
cmds.vray("vfbControl","-setregion","reset")
if rrstate == 1:
cmds.vray("vfbControl","-setregionenabled",1)
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
return(reg)
def cancelOPs(*args):
global cancel
cancel = 1
raise Exception("quitting renders")
def set_threshhold(floatField_thrhld,*args):
threshhold_value = cmds.floatField(floatField_thrhld,value = True,query = True)
cmds.setAttr('vraySettings.dmcThreshold',threshhold_value)
def set_resolution(intField_res,*args):
intField_res_value = cmds.intField(intField_res,value = True,query = True)
cmds.setAttr('vraySettings.width',intField_res_value)
cmds.setAttr('vraySettings.height',intField_res_value)
def renthumbsWin():
name = "Batch_Review"
global gReg
gReg = ('0','0','0','0')
zeroes = ('0','0','0','0')
windowSize = (200,100)
if (cmds.window(name, exists = True)):
cmds.deleteUI(name)
window = cmds.window(name, title = name, width = 350, height = 50,bgc = (.2,.2,.2), s = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = "preset quality: ")
checkBoxLow = cmds.checkBox(label = "low", value = False)
checkBoxMid = cmds.checkBox(label = "mid", value = True,)
checkBoxHigh = cmds.checkBox(label = "high", value = False)
cmds.text(label = " ")
cmds.text(label = "resolution: ")
intField_res = cmds.intField(v = 1000,width = 45)
#print 'intField_res = ',intField_res
cmds.intField(intField_res, changeCommand = partial(set_resolution,intField_res),edit = True)
cmds.text(label = " ")
cmds.text(label = "threshold: ")
floatField_thrhld = cmds.floatField(v = .5,width = 45)
cmds.floatField(floatField_thrhld, changeCommand = partial(set_threshhold,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxLow, changeCommand = partial(checkBoxCheckLow,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld), edit = True)
cmds.checkBox(checkBoxMid, changeCommand = partial(checkBoxCheckMid,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxHigh, changeCommand = partial(checkBoxCheckHigh,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.rowLayout("nameRowLayout02", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout03", numberOfColumns = 5, parent = "mainColumn")
renderButton = cmds.button(label = "render",width = 100, bgc = (.6,.8,1) )
cmds.text(label = " ")
cmds.button(label = "cancel renders", command = partial(cancelOPs),bgc = (1,.3,.3) )
cmds.rowLayout("nameRowLayout04", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout05", numberOfColumns = 10, parent = "mainColumn")
checkBoxRenderRegion = cmds.checkBox(label = "use render region", value = False)
cmds.text(label = " ")
cmds.text(label = " ")
reg = cmds.vray("vfbControl","-getregion")
if reg != gReg and reg != zeroes:
gReg = reg
cmds.vray("vfbControl","-setregion","reset")
cmds.checkBox(checkBoxRenderRegion,changeCommand = partial(rrCheckbox,checkBoxRenderRegion,reg),edit = True)
cmds.rowLayout("nameRowLayout06", numberOfColumns = 10, parent = "mainColumn")
AOVstate = cmds.getAttr("vraySettings.relements_enableall")
checkBoxAOV = cmds.checkBox(label = "elements", value = AOVstate)
cmds.checkBox(checkBoxAOV,changeCommand = partial(checkBoxAOVchange,checkBoxAOV),edit = True)
cmds.button(renderButton,command = partial(renderThumbs,checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld),edit = True)
cmds.showWindow()
def main():
renthumbsWin()
main()
so my program takes a directory with excel files with one line and combine them all into one.
The gui has two buttons one to choose the path and one to save the wanted path.
I created a gui class and im basically trying to pass the OptionMenu chosen text forward after an event was made, but an exception is raised and Im struggling with,
long story short:
import os
from tkinter import *
from tkinter import filedialog
from CombineExcelFiles import *
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('חלבי')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
def upload():
global basepath
basepath = filedialog.askdirectory()
def save():
#print(self.variable.get())
try: #This is line 25
basepath
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
writeToFile(data, file_list, download_path, master.variable.get())
except NameError:
tkinter.messagebox.showerror('ERROR', 'בחר תיקיית מקור')
This is the writeToFile from CombineExcelFiles:
def writeToFile(data, files,download_path,variable):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
.
.
.
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + variable + str(temp_date.month) + '-' +
str(temp_date.year) + '.xlsx' )
The error that was given is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\******\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/******/CombineExcels/mainProject.py", line 25, in save
print(self.variable.get())
TypeError: writeToFile() missing 1 required positional argument: 'variable'
Thank you in advance
Edit, Ive put the code n one file so it will be runnable:
import os
from tkinter import *
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.styles.borders import Border, Side
from datetime import datetime
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('בחר מרשימה')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
#START GUI PROPERTIES
def upload(self):
global basepath
basepath = filedialog.askdirectory()
print(master)
def save(self):
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
print(self.variable.get())
writeToFile(data, file_list, download_path)
#STOP GUI PROPERTIES
def getData(self, basepath, file_list):
a = []
for file in file_list:
load_workbook(basepath + '/' + file)
tempData = []
for cell in temp['Sheet1']:
for value in cell:
if value.value == None:
continue
else:
tempData.append(value.value)
data.append(tempData)
return data
def fitToCell(self, ws): #get used columns and than fit cell's width into length of letters
dict = {}
for cell in ws:
for value in cell:
temp = str(value.value)
if temp:
if value.coordinate[0] not in dict:
dict[value.coordinate[0]] = len(temp)
elif len(temp) > dict[value.coordinate[0]]:
dict[value.coordinate[0]] = len(temp)
for col in dict:
ws.column_dimensions[col].width = dict[col]
return ws
def writeToFile(self, data, files,download_path):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
print(ws.evenHeader.right.text)
if self.variable.get() == 'חלבי':
ws['C2'].value = 'חלב רצוי'
ws['C2'].alignment = center
ws['C2'].border = br
ws['D2'].value = 'חלב מצוי'
ws['D2'].alignment = center
ws['D2'].border = br
ws['E2'].value = 'קקאו רצוי'
ws['E2'].alignment = center
ws['E2'].border = br
ws['F2'].value = 'קקאו מצוי'
ws['F2'].alignment = center
ws['F2'].border = br
ws['G2'].value = 'שמן רצוי'
ws['G2'].alignment = center
ws['G2'].border = br
ws['H2'].value = 'שמן מצוי'
ws['H2'].alignment = center
ws['H2'].border = br
ws['I2'].value = 'סוכר רצוי'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'סוכר מצוי'
ws['J2'].alignment = center
ws['J2'].border = br
ws['I2'].value = 'מספר מתכון'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'זמן ייצור'
ws['J2'].alignment = center
ws['J2'].border = br
ws['K2'].value = 'תאריך ייצור'
ws['K2'].alignment = center
ws['K2'].border = br
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['J' + str(row)].alignment = center
ws['J' + str(row)].border = br
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
ws['K' + str(row)].border = br
ws['K' + str(row)].alignment = center
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + self.variable.get() +' ' + str(temp_date.month) + '-' + str(temp_date.year) + '.xlsx' )
window = Tk()
my_gui = GUI(window)
#print(my_gui.variable.get())
window.mainloop()
This is the error:
runfile('C:/Users/*****/Desktop/תכנות/untitled2.py',
wdir='C:/Users/*****/Desktop/תכנות')
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\*****\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/*****/CombineExcels/mainProject.py", line 25, in save
TypeError: writeToFile() missing 1 required positional argument: 'var'
For some reason it keeps returning from another path
solved it, had put all the methods inside the object, while the events func inside the init.
also i ran too many times the program so the errors were not related to my code...
I'm trying to add a scrollbar to my tkinter window which stays in place and scrolls through a frame. However, whenever I launch the application, the scrollbar is greyed out. Here is the relevant excerpt from my code:
self.bigFrame = ttk.Frame(self,width = 1080,height = 500)
self.hsb = tk.Scrollbar(self.bigFrame,orient = "horizontal")
self.hsb.pack(side = TOP, fill = X)
self.treeCanvas = tk.Canvas(self.bigFrame,width = 1080,height = 500,xscrollcommand = self.hsb.set)
self.treeFrame = tk.Frame(self.treeCanvas,width = 1080,height = 500)
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
self.treeCanvas.config(scrollregion = self.treeCanvas.bbox("all"))
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
self.hsb.config(command = self.treeCanvas.xview)
self.tree = ttk.Treeview(self.treeFrame,selectmode='browse',height = 100, columns = ('name','purchaseprice','previousprices','listingprice','buyingformat','postage','fees','potprofit','offers','viewcount','sold','offertaken','username','dispatch','delivered','returned','relist','feedback'))
self.tree.heading('#0',text = 'saleID',anchor = 'w')
self.tree.heading('name',text = "Item Name",anchor = 'w')
self.tree.heading('purchaseprice',text = "Purchase Price",anchor = 'w')
self.tree.heading('previousprices',text = "Previous Prices",anchor = 'w')
self.tree.heading('listingprice',text = "Listing Price", anchor = 'w')
self.tree.heading('buyingformat',text = "Buying Format",anchor = 'w')
self.tree.heading('postage',text = "Postage",anchor = 'w')
self.tree.heading('fees',text = "Fees",anchor = 'w')
self.tree.heading('potprofit',text = "Potential Profit",anchor = 'w')
self.tree.heading('offers',text = "Best Offer",anchor = 'w')
self.tree.heading('viewcount',text = "Viewcount",anchor = 'w')
self.tree.heading('sold',text = "Sold?",anchor = 'w')
self.tree.heading('offertaken',text = "Offer Taken?",anchor = 'w')
self.tree.heading('username',text = "Username",anchor = 'w')
self.tree.heading('dispatch',text = "Dispatched?",anchor = 'w')
self.tree.heading('delivered',text = "Delivered?",anchor = 'w')
self.tree.heading('returned',text = "Returned?",anchor = 'w')
self.tree.heading('relist',text = "Relisted?",anchor = 'w')
self.tree.heading('feedback',text = "Feedback",anchor = 'w')
self.tree.pack(side = BOTTOM, fill = X)
self.bigFrame.grid(row = 11,column = 0,columnspan = 100,pady=(5,0),sticky = 'nw')
self.bigFrame.grid_rowconfigure(0,weight = 1)
self.bigFrame.grid_columnconfigure(0,weight = 1)
self.bigFrame.grid_propagate(False)
I'm sure it's an issue with the ordering of lines, but none of the orders I've tried have worked.
The reason your scrollbar is greyed out is because you are missing this line:
self.treeFrame.update_idletasks()
Below implemented in the rest of your code.
...
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
# add this
self.treeFrame.update_idletasks()
bbox = self.treeCanvas.bbox(tk.ALL)
# Update this
self.treeCanvas.config(scrollregion=bbox, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT)
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
...
Hopefully this answer helps, if not you could try the last answer from this question, which helped me alot.